Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 20/ 160
01. SQL Foundations & Relational Concepts

SQL Execution Order vs Logical Writing Order

Contrast how you write SELECT vs how the engine logically processes clauses.

IntermediateFROM · WHERE · SELECT3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

The classic errorQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  department,3  COUNT(*) AS n4FROM5  employees6WHERE7  n > 58GROUP BY9  department
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/9
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected error
ERROR: column "n" does not exist

Note: Exact wording and code vary by database. The SELECT alias is not available to WHERE because WHERE is evaluated before SELECT.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

Filtering on a window functionQuery example
1Input dataStart from the source rows or state that the statement sees.
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  *3FROM4  (5    SELECT6      *,7      ROW_NUMBER() OVER (8        PARTITION BY9          user_id10        ORDER BY11          created_at12      ) AS rn13    FROM14      orders15  ) t16WHERE17  rn = 1
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/17
3OutputInspect the representative rows, affected-row count, plan, or command status.
First order for each user2 sample rows
First order for each user
iduser_idcreated_atrn
10172026-11-03 08:00:001
20582026-11-05 10:30:001

Note: Assumes these are the earliest orders in the sample; SELECT * preserves the inner query columns in a representative schema.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

: the outer WHERE runs after the inner SELECT computed rn.

Key takeaway: Logical order decides what you get; the optimizer decides how.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Row source

FROM and JOIN

Tables are read and joined (ON conditions applied) into one working set of rows. Every later clause works on this set.

SQL at this step
1FROM2  orders o3  JOIN customers c ON c.id = o.customer_id
What to watch at this step
Sees
all joined rows
Aliases
table aliases only
Tip: use ← → to move between steps

When 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

WHERE
Best for: Conditions on individual rows (status, date range)

Strengths: Runs early and shrinks the data before grouping; can use indexes.

Watch out: Can't use aggregates or SELECT aliases.

HAVING
Best for: Conditions on aggregates (groups with more than 5 orders)

Strengths: Sees the aggregate values of each group.

Watch out: Runs after grouping, so row-level filters here waste work.

Subquery or CTE + outer WHERE
Best for: Filtering on an alias or a window function result

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(*) > 5 instead of HAVING 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?
Interview tip: Recite the order once (FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT), then prove you understand it with the alias-in-WHERE error and how you'd fix it.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
Sorting & Limiting Results (ORDER BY, ASC/DESC, LIMIT, OFFSET)
Next topic
Aggregate Functions (COUNT, SUM, AVG, MIN, MAX)