Logical Execution Order in SQL
Written SELECT-first, executed FROM-first — why aliases fail in WHERE
SQL is written SELECT … FROM … WHERE … but executed FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT. WHERE runs before SELECT, so it cannot see column aliases; ORDER BY runs after, so it can. GROUP BY also precedes SELECT, which is why only grouped or aggregated expressions are valid there.
FROM loads first
The engine starts from the table (or JOIN result) — not from SELECT. Everything downstream sees those rows.
WHERE filters early
Rows are trimmed before grouping or projection. No aliases exist yet, no aggregates — only base columns and expressions over them.
GROUP BY + HAVING bucket
Survivors are bucketed, aggregates computed per bucket, then HAVING trims buckets. Aggregates are born here.
SELECT, ORDER BY, LIMIT finish
Projection and aliases appear, then ORDER BY sorts (aliases visible) and LIMIT caps. Alias-in-WHERE errors are execution order made visible.
1SELECT salary * 12 AS annual FROM employees WHERE annual > 500000; -- INVALID2SELECT salary * 12 AS annual FROM employees ORDER BY annual DESC; -- VALID
| name | annual |
|---|---|
| Cynthia | 1092000 |
| Alice | 1020000 |
| Farid | 876000 |
The first query fails because WHERE runs before the alias annual exists — repeat the expression or filter outside. The second works because ORDER BY runs after SELECT.
Alias invisible in WHERE
WHERE runs before SELECT, so the alias does not exist yet.
1-- INVALID: annual unknown in WHERE2-- SELECT salary * 12 AS annual FROM employees WHERE annual > 500000;3-- VALID: repeat expression4SELECT name, salary * 12 AS annual FROM employees WHERE salary * 12 > 500000 ORDER BY annual DESC;
| name | annual |
|---|---|
| Cynthia | 1092000 |
| Alice | 1020000 |
| Farid | 876000 |
HAVING sits after grouping
Aggregates can only be filtered after they are computed.
1SELECT department, AVG(salary) AS avg_pay FROM employees GROUP BY department HAVING AVG(salary) > 60000;
| department | avg_pay |
|---|---|
| Engineering | 83000 |
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Take the queries you just visualized and see the data structures that power real databases.