Logical Order of Query Processing in SQL
suggest change/*(8)*/ SELECT /*9*/ DISTINCT /*11*/ TOP
/*(1)*/ FROM
/*(3)*/ JOIN
/*(2)*/ ON
/*(4)*/ WHERE
/*(5)*/ GROUP BY
/*(6)*/ WITH {CUBE | ROLLUP}
/*(7)*/ HAVING
/*(10)*/ ORDER BY
/*(11)*/ LIMIT
The order in which a query is processed and description of each section.
VT stands for ‘Virtual Table’ and shows how various data is produced as the query is processed
- FROM: A Cartesian product (cross join) is performed between the first two tables in the FROM clause, and as a result, virtual table VT1 is generated.
- ON: The
ONfilter is applied to VT1. Only rows for which the condition isTRUEare inserted into VT2. - OUTER (join): If an
OUTER JOINis specified (as opposed to aCROSS JOINor anINNER JOIN), rows from the preserved table or tables for
which a match was not found are added to the rows from VT2 as outer rows, generating VT3. If more than two tables appear in the FROM clause,
steps 1 through 3 are applied repeatedly between the result of the last join and the next table in the FROM clause until all tables are processed.
- WHERE: The
WHEREfilter is applied to VT3. Only rows for which the condition isTRUEare inserted into VT4. - GROUP BY: The rows from VT4 are arranged in groups based on the column list in the
GROUP BYclause. VT5 is generated. - CUBE or ROLLUP: Supergroups (groups of groups) are added to the rows from VT5, generating VT6.
WITH CUBEandWITH ROLLUPin the sketch above are old SQL Server syntax. Standard SQL writesGROUP BY CUBE (...)orGROUP BY ROLLUP (...). - HAVING: The
HAVINGfilter is applied to VT6. Only groups for which the condition isTRUEare inserted into VT7. - SELECT: The select list is processed, generating VT8.
- DISTINCT: Duplicate rows are removed from VT8. VT9 is generated.
- ORDER BY: The rows from VT9 are sorted according to the column list in the
ORDER BYclause. A cursor is generated (VC10). - TOP: The specified number or percentage of rows is selected from the beginning of VC10. Table VT11 is generated and returned to the caller.
LIMIThas a similar role in some dialects, such as PostgreSQL and Netezza.TOPis SQL Server syntax.WHERErejectsUNKNOWNas well asFALSE, including comparisons withNULL.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents