← Lessons

quiz vs the machine

Silver1050

Databases

The Select Query Execution Order

SQL reads top to bottom but runs in a different order, which explains why aliases and aggregates behave the way they do.

4 min read · intro · beat Silver to climb

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.

Check yourself

Answer to earn rating on the learn ladder.

1. Why can you usually not filter on a SELECT alias inside WHERE?

2. Which clause runs first in logical order?

3. Where can a SELECT alias be safely referenced?