SQL Query Execution Order
The logical order clauses are actually evaluated in — not the order you type them — and why it explains rules that otherwise seem arbitrary.
2 min read
A SELECT query is written in one order — SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT — but the database doesn't evaluate the clauses in that order. Knowing the actual logical order clears up several rules from earlier lessons that otherwise look inconsistent.
The logical order of evaluation
1. FROM / JOIN — determine the working set of rows across all tables
2. WHERE — filter individual rows
3. GROUP BY — group the remaining rows
4. HAVING — filter groups
5. SELECT — compute the selected columns and expressions
6. ORDER BY — sort the result
7. LIMIT / OFFSET — cap the number of rows returned
SELECT is written first but evaluated almost last — everything the query ultimately returns is computed only after the rows have already been gathered, filtered, and grouped.
Why this explains WHERE vs. HAVING
This is exactly the distinction from the earlier HAVING vs WHERE lesson, now grounded in why it's true: WHERE (step 2) runs before GROUP BY (step 3) even happens, so it has no aggregate results to filter on yet — only raw rows. HAVING (step 4) runs after grouping, so it can filter on the aggregate values computed by then.
Why you can't reference a SELECT alias in WHERE
-- Error in most databases
SELECT price * quantity AS total FROM order_items WHERE total > 100;WHERE (step 2) is evaluated before SELECT (step 5) — so at the point WHERE runs, the alias total doesn't exist yet; it isn't computed until step 5. The fix is either repeating the expression in WHERE, or wrapping the query in a subquery (covered a few lessons back) so the alias is computed first and the outer query filters on it afterward.
SELECT total FROM (
SELECT price * quantity AS total FROM order_items
) AS sub
WHERE total > 100;Why ORDER BY can reference a SELECT alias
SELECT price * quantity AS total FROM order_items ORDER BY total DESC;This one works precisely because ORDER BY (step 6) runs after SELECT (step 5) — by the time sorting happens, total has already been computed and is available to sort by. It's the same underlying rule as the WHERE case, just landing on the opposite answer because of where each clause sits in the actual evaluation order.
Why this is worth memorizing
Once this order is second nature, a whole category of "why doesn't this query work" confusion disappears — every one of these rules follows directly from the same seven-step sequence, rather than needing to be memorized as unrelated special cases.
The final lesson of this course zooms out from SQL's mechanics to compare relational databases against NoSQL alternatives, and where each one actually fits.