Logical processing order 🎥
Warning
Confusingly, the order in which things are done in a SELECT
statement is not exactly the same as the order in which they are written.
This is because SQL code was designed to be written in a way that is easy to read and write, rather than to reflect what happens under the hood.
The written order of a SELECT
statement
This has been mentioned in each of the clauses' respective pages, but the lexical (written) order of a SELECT
statement is as follows:
SELECT
DISTINCT
TOP
FROM
JOIN
ON
WHERE
GROUP BY
WITH CUBE
orWITH ROLLUP
HAVING
WINDOW
ORDER BY
The logical processing order of a SELECT
statement
The logical processing order of a SELECT
statement is not the same as the written order.
A big part of understanding SQL is understanding the order in which things are done in a SELECT
statement.
Do joins happen before or after the
WHERE
clause? Are rows deduplicated before being aggregated? Are rows ordered before being "topped" (withTOP
)?
This is important to understand because it can affect the result of your query.
As per the Microsoft SQL Server documentation, the logical processing order of a SELECT
statement is as follows:
FROM
ON
JOIN
WHERE
GROUP BY
WITH CUBE
orWITH ROLLUP
HAVING
SELECT
(andOVER
/WINDOW
)DISTINCT
ORDER BY
TOP
SQL has this disparity between the written code and the order in which it is processed because SQL is a "declarative" language. You don't need to know what this means, but it's just a fancy way of saying that you tell SQL what you want, not how to get it.
Further reading
Check out the official Microsoft documentation for more information on the logical processing order of the select statement at: