Logical Flow of the Query Statement
The best way to think through a SQL DML statement is to walk through the query's logical flow (see Figure 2).
Because SQL is a declarative language, the logical flow may or may not
be the actual physical flow that SQL Server's query processor uses to
execute the query. Nor is the logical flow the same as the query
syntax. Regardless, think through a query in the following order.
Following is a more detailed explanation of the logical flow of the query. Every step except step 4 is optional:
1. [From]: The query begins by assembling the initial set of data, as specified in the FROM portion of the SELECT statement.
2. [Where]: The filter process is actually the WHERE clause, selecting only those rows that meet the criteria.
3. [Aggregations]:
SQL can optionally perform aggregations on the data set, such as
finding the average, grouping the data by values in a column, and
filtering the groups.
4. Column Expressions: The SELECT list is processed, and any expressions are calculated .
5. [Order By]: The resulting rows are sorted according to the ORDER BY clause, which can be ascending or descending. The default sort order is ascending.
6. [Over]: Windowing and ranking functions can provide a separately ordered view of the results with additional aggregate functions.
7. [Distinct]: Any duplicate rows are eliminated from the result set.
8. [Top]:
After the rows are selected, the calculations are performed, and the
data is sorted into the wanted order, SQL can restrict the output to
the top few rows.
9. [Insert, Update, Delete]:
The final logical step of the query is to apply the data modification
action to the results of the query.
10. [Output]:
The inserted and deleted virtual tables (normally only used with a
trigger) can be selected and returned to the client, inserted into a
table, or serve as a data source to an outer query.
11. [Union]: The results of multiple queries can be stacked or combined using a union command .
As more complexity has been added to the SQL SELECT
command over the years, how to think through the logical flow has also
become more complex. In various sources, you can find minor differences
in how SQL professionals view the logical flow. That's OK — it's just a
way to think through a query.
As you begin to think in terms of the SQL SELECT statement, rather than in terms of the graphical user interface, understanding the flow of SELECT and how to read the query execution plan can help you think through and develop difficult queries.
Physical Flow of the Query Statement
SQL Server can take the SELECT statement and develop an optimized query execution plan, which may not be in the execution order you would guess (see Figure 3).
The indexes available to the SQL Server Query Optimizer also affect the
query execution plan.