SQL Execution Order vs Logical Writing Order
Contrast how you write SELECT vs how the engine logically processes clauses.
In plain words
SQL is written in one order but run in another: first pick the tables, then filter rows, then group, then choose the columns, then sort and cut.
Think of it like…
Cooking from a recipe: get the ingredients out (FROM), throw away the bad ones (WHERE), sort them into bowls (GROUP BY), drop bowls that are too small (HAVING), plate them (SELECT), line the plates up (ORDER BY) and serve the first few (LIMIT).
Where you’ve seen it
SELECT price * qty AS total FROM order_items WHERE total > 100 fails with "column total does not exist" because WHERE runs before SELECT creates the alias. Repeat the expression in WHERE, or compute it in a subquery or CTE first.
Words you’ll hear
- Logical order
- The order clauses are conceptually evaluated in, regardless of how you write them.
- Alias scope
- A SELECT alias exists only for later steps: ORDER BY everywhere, and GROUP BY in PostgreSQL and MySQL.
- Row filter vs group filter
- WHERE filters rows before grouping; HAVING filters groups after.
- Physical plan
- What the optimizer actually runs. It can reorder work as long as the result matches the logical order.
Visual diagram
Theory & example queries
Why the order matters
Each clause receives the output of the previous step. WHERE sees individual rows from FROM/JOIN, so it can't reference aggregates (no groups exist yet) or SELECT aliases (they haven't been computed).
ORDER BY runs after SELECT, so it can sort by an alias or expression. LIMIT and OFFSET run last, which is why ORDER BY … LIMIT 10 returns the top 10 rather than 10 arbitrary rows that are then sorted.
SELECT department, COUNT(*) AS nFROM employeesWHERE n > 5GROUP BY departmentPostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Expected error
Note: Exact wording and code vary by database. The SELECT alias is not available to WHERE because WHERE is evaluated before SELECT.
fails. Move the condition to HAVING COUNT(*) > 5, which runs after grouping.
Key takeaway: WHERE filters rows, HAVING filters groups, ORDER BY can use aliases.
Logical order vs what the engine actually does
The logical order defines what result you get, not how it is computed. The optimizer pushes filters down, reorders joins, or uses an index to avoid a sort, as long as the final result is the same.
Window functions are evaluated with SELECT, after WHERE, GROUP BY and HAVING. That's why you can't filter on ROW_NUMBER() in WHERE: compute it in a subquery or CTE and filter outside, or use QUALIFY where it exists (Snowflake, BigQuery, DuckDB). Dialects also differ at the edges: PostgreSQL and MySQL accept GROUP BY alias or GROUP BY 1, SQL Server doesn't.
| id | customer_id | status | amount | coupon_code |
|---|---|---|---|---|
| 101 | 1 | paid | 249 | NULL |
| 102 | 2 | paid | 120 | WELCOME10 |
| 103 | 1 | shipped | 89.5 | NULL |
SELECT *FROM ( SELECT *, ROW_NUMBER() OVER ( PARTITION BY user_id ORDER BY created_at ) AS rn FROM orders ) tWHERE rn = 1PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
First order for each user2 sample rows
| id | user_id | created_at | rn |
|---|---|---|---|
| 101 | 7 | 2026-11-03 08:00:00 | 1 |
| 205 | 8 | 2026-11-05 10:30:00 | 1 |
Note: Assumes these are the earliest orders in the sample; SELECT * preserves the inner query columns in a representative schema.
: the outer WHERE runs after the inner SELECT computed rn.
Key takeaway: Logical order decides what you get; the optimizer decides how.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
FROM and JOIN
Tables are read and joined (ON conditions applied) into one working set of rows. Every later clause works on this set.
FROM orders o JOIN customers c ON c.id = o.customer_idWhen to use it & trade-offs
What it is
You write SQL as SELECT → FROM → WHERE → GROUP BY → HAVING → ORDER BY → LIMIT, but the database evaluates it logically as FROM/JOIN → WHERE → GROUP BY → HAVING → SELECT → DISTINCT → ORDER BY → LIMIT. Each step only sees the output of the steps before it.
Why it matters: This order explains errors that trip people up constantly: why a SELECT alias can't be used in WHERE, why aggregates aren't allowed in WHERE, and why ORDER BY can use an alias. Interviewers ask it because it shows whether you understand SQL or just memorised syntax.
When to reach for it
- Debugging "column does not exist" errors on aliases
- Deciding between WHERE and HAVING
- Explaining why a window function can't be filtered in WHERE
When to avoid or be careful
- Putting row-level filters in HAVING: it works, but filters after the expensive grouping
- Relying on GROUP BY alias support if your SQL also has to run on SQL Server
- Assuming the engine physically runs clauses in this order; it's a logical model
Where to put a condition
Strengths: Runs early and shrinks the data before grouping; can use indexes.
Watch out: Can't use aggregates or SELECT aliases.
Strengths: Sees the aggregate values of each group.
Watch out: Runs after grouping, so row-level filters here waste work.
Strengths: Makes the computed column available to a later step.
Watch out: A little more verbose.
Interview signals & numbers to know
When this topic comes up
- “What is the order of execution of a SQL query?”
- “Why can't I use the alias in WHERE?”
- WHERE vs HAVING
- Filtering on ROW_NUMBER()
- “aggregate functions are not allowed in WHERE”
Benchmarks & rules of thumb
- 1
- FROM / JOIN
- 2
- WHERE
- 3–4
- GROUP BY → HAVING
- 5–8
- SELECT → DISTINCT → ORDER BY → LIMIT
Common mistakes & follow-ups
Common interview mistakes
- Using a SELECT alias in WHERE and getting "column does not exist".
- Writing
WHERE COUNT(*) > 5instead ofHAVING COUNT(*) > 5. - Filtering a window function result at the same query level instead of in an outer query.
Likely interviewer follow-ups
- Why can ORDER BY use a column alias when WHERE can't?
- Where do window functions sit in the logical order, and how do you filter on them?
- Does the database physically execute clauses in this order? What is the optimizer allowed to change?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply SQL Execution Order vs Logical Writing Order with hands-on SQL practice and interview Q&A.