← Lessons

quiz vs the machine

Silver1050

Databases

The Real SELECT Execution Order

SQL is written top down but the engine evaluates clauses in a different order.

4 min read · intro · beat Silver to climb

Written Order Versus Logical Order

You write a query starting with SELECT, but the database does not run it that way. The logical processing order decides what names exist when each clause runs, and understanding it removes a whole class of confusing errors.

The Logical Steps

  • FROM and JOIN build the working set of rows from the source tables.
  • WHERE filters individual rows before any grouping happens.
  • GROUP BY collapses rows into groups.
  • HAVING filters those groups.
  • SELECT computes the output columns and any aliases.
  • ORDER BY sorts the final result.
  • LIMIT trims how many rows come back.

Why It Matters

Because SELECT runs after WHERE, a column alias defined in SELECT is usually not visible in WHERE. Because GROUP BY runs before SELECT, aggregates are available to HAVING but row level columns are not. Knowing the order tells you exactly which names are legal in each clause.

Key idea

SQL is processed FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT, so names become available only when their producing clause has run.

Check yourself

Answer to earn rating on the learn ladder.

1. Why can a SELECT alias usually not be used in the WHERE clause?

2. Which clause runs first in logical processing?