Written Order Is Not Run Order
You write a query as SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY. The database runs it in a different sequence. Knowing that sequence removes most beginner confusion.
The Logical Order
The engine processes clauses in this logical order:
- FROM and JOIN build the working set of rows.
- WHERE filters individual rows before grouping.
- GROUP BY collapses rows into groups.
- HAVING filters whole groups.
- SELECT computes the output columns and aliases.
- ORDER BY sorts the final result.
- LIMIT trims the number of rows returned.
Why It Matters
Because SELECT runs after WHERE and GROUP BY, a column alias defined in SELECT is usually not visible in WHERE. That is why filtering on a computed alias often fails. ORDER BY runs last, so it can see SELECT aliases.
Key idea
SQL clauses run FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT, which is why aliases work in ORDER BY but not in WHERE.