Skip to content

SQL Order of Execution: How a Query Really Runs, With Examples

Gulab Chand Tejwani

Gulab Chand Tejwani

PMP · PL-300 · Microsoft Certified Trainer

· 10 min read

SQLSQL BasicsSQL Interview QuestionsData AnalysisQuery Writing
SQL Order of Execution: How a Query Really Runs, With Examples

A SQL query is written starting with SELECT, but it is logically processed in this order: FROM (and JOINs) → WHERE → GROUP BY → HAVING → SELECT (including window functions) → DISTINCT → ORDER BY → LIMIT/OFFSET. Knowing that order explains most of the confusing errors beginners hit: why a column alias works in ORDER BY but not in WHERE, why SUM() can't go in WHERE, and why you need a subquery to filter on ROW_NUMBER().

I'm Gulab Chand Tejwani from TechNet Consultancy. "Explain the order of execution of a SQL query" is one of the most common SQL interview questions I hear about from students, and it's also the idea that, once it clicks, makes people noticeably faster at fixing their own queries. Below is the order, one query traced through it step by step, and the five errors it explains. Every query here was run in PostgreSQL 16.

What is the order of execution of a SQL query?

StepClauseWhat it does
1FROM and JOINPicks the tables and combines them into one working set of rows
2WHERERemoves rows that don't match the condition
3GROUP BYCollapses the remaining rows into groups
4HAVINGRemoves groups that don't match the condition
5SELECTCalculates the output columns, aliases and window functions
6DISTINCTRemoves duplicate output rows
7ORDER BYSorts the result
8LIMIT / OFFSET (or TOP, FETCH)Keeps only the requested rows
Logical order of processing in a SELECT query

A useful way to remember it: each step can only use what earlier steps produced. WHERE runs before SELECT, so it can't see anything SELECT creates.

The sample data

Two small tables, used for every example:

CREATE TABLE customers (customer_id int PRIMARY KEY, name text, city text);
CREATE TABLE orders (order_id int PRIMARY KEY, customer_id int,
                     order_date date, amount numeric, status text);

INSERT INTO customers VALUES
 (1,'Asha','Anand'), (2,'Ravi','Vadodara'), (3,'Meera','Anand'), (4,'Karan','Ahmedabad');

INSERT INTO orders VALUES
 (101,1,'2026-01-05',1200,'delivered'), (102,1,'2026-01-19',800,'cancelled'),
 (103,2,'2026-01-21',4500,'delivered'), (104,3,'2026-02-02',650,'delivered'),
 (105,2,'2026-02-10',3000,'delivered'), (106,3,'2026-02-14',2200,'delivered'),
 (107,1,'2026-02-20',1500,'delivered');

The data is illustrative. Karan has no orders, and order 102 is cancelled; both matter later.

How does one query move through the steps?

Here's a query that uses every clause: delivered revenue by city, only for cities above 2,000, highest first.

SELECT c.city, COUNT(*) AS orders, SUM(o.amount) AS revenue
FROM orders o
JOIN customers c ON c.customer_id = o.customer_id
WHERE o.status = 'delivered'
GROUP BY c.city
HAVING SUM(o.amount) > 2000
ORDER BY revenue DESC
LIMIT 5;
cityordersrevenue
Vadodara27500
Anand45550
Delivered revenue by city

Tracing it:

  1. FROM / JOIN matches each of the 7 orders to its customer. Karan has no orders, so an inner join drops him.
  2. WHERE removes order 102 (cancelled). Six rows remain.
  3. GROUP BY makes two groups: Anand (orders 101, 104, 106, 107) and Vadodara (103, 105).
  4. HAVING keeps groups whose total is above 2,000. Both pass: 5,550 and 7,500.
  5. SELECT calculates city, COUNT(*) and SUM(amount), and names them orders and revenue.
  6. DISTINCT isn't used here.
  7. ORDER BY sorts by revenue. This works because the alias already exists after step 5.
  8. LIMIT keeps up to 5 rows.

Which errors does the order of execution explain?

1. Using a column alias in WHERE

SELECT order_id, amount * 1.18 AS amount_with_gst
FROM orders
WHERE amount_with_gst > 1000;
-- ERROR: column "amount_with_gst" does not exist

WHERE (step 2) runs before the alias is created in SELECT (step 5). Repeat the expression in WHERE. The alias is fine in ORDER BY, which runs after SELECT:

SELECT order_id, amount * 1.18 AS amount_with_gst
FROM orders
WHERE amount * 1.18 > 3000
ORDER BY amount_with_gst DESC;

That returns order 103 (5310.00) and order 105 (3540.00).

2. Putting an aggregate in WHERE

SELECT customer_id
FROM orders
WHERE SUM(amount) > 3000
GROUP BY customer_id;
-- ERROR: aggregate functions are not allowed in WHERE

WHERE works on single rows before any grouping, so there's no group to sum yet. Conditions on totals, counts and averages go in HAVING:

SELECT customer_id, SUM(amount) AS total
FROM orders
GROUP BY customer_id
HAVING SUM(amount) > 3000;

3. Using a SELECT alias in HAVING or GROUP BY

In PostgreSQL, HAVING total > 3000 fails with column "total" does not exist, so repeat the aggregate as above. Databases differ here, which is worth saying in an interview:

  • PostgreSQL and MySQL accept an output alias in GROUP BY (for example GROUP BY m where m is EXTRACT(MONTH FROM order_date)).
  • MySQL also accepts an alias in HAVING; PostgreSQL doesn't.
  • SQL Server accepts neither, because it follows the logical order strictly.

Repeating the expression works everywhere, so it's the safe habit.

4. Filtering on a window function

"Latest order per customer" is a classic. This fails:

SELECT order_id,
       ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC, order_id DESC) AS rn
FROM orders
WHERE rn = 1;
-- ERROR: column "rn" does not exist

Window functions are calculated in the SELECT step, after WHERE has already run. Calculate the number in a CTE or subquery, then filter outside it:

WITH ranked AS (
  SELECT order_id, customer_id, order_date, amount,
         ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC, order_id DESC) AS rn
  FROM orders
)
SELECT customer_id, order_id, order_date, amount
FROM ranked
WHERE rn = 1
ORDER BY customer_id;
customer_idorder_idorder_dateamount
11072026-02-201500
21052026-02-103000
31062026-02-142200
Latest order per customer

Some databases (Snowflake, BigQuery, Databricks and recent DuckDB) add a QUALIFY clause that filters window results directly. It's not standard SQL, so the CTE is the portable answer.

5. ORDER BY a column that DISTINCT removed

SELECT DISTINCT city FROM customers ORDER BY name;
-- ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list

After DISTINCT (step 6) there's one row per city, and "Anand" covers two names, so there's no single name to sort by. Order by a selected column, or by an aggregate in a GROUP BY query instead.

Why does WHERE versus ON matter for a LEFT JOIN?

This one is about the join step, and it silently gives wrong numbers instead of an error. Count delivered orders for every customer, including those with none:

-- Filter in WHERE: Karan disappears
SELECT c.customer_id, c.name, COUNT(o.order_id) AS delivered_orders
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
WHERE o.status = 'delivered'
GROUP BY c.customer_id, c.name;

That returns three rows. The LEFT JOIN keeps Karan with NULL order columns, then WHERE o.status = 'delivered' throws him out, because NULL isn't equal to anything. Move the condition into the join:

SELECT c.customer_id, c.name, COUNT(o.order_id) AS delivered_orders
FROM customers c
LEFT JOIN orders o
  ON o.customer_id = c.customer_id AND o.status = 'delivered'
GROUP BY c.customer_id, c.name
ORDER BY c.customer_id;

Now Karan appears with 0. Grouping by customer_id as well as name keeps two different customers who share a name in separate rows. The rule: on the right table of a LEFT JOIN, conditions in ON decide what matches, and conditions in WHERE decide what survives. More on joins in SQL joins explained with examples.

Is the logical order the same as the physical order?

No. The logical order defines what the result must be. The query optimiser is free to run things in a different physical order as long as the result is the same. For example, it may push a WHERE filter down into the table scan, use an index to avoid sorting for ORDER BY, or stop reading early because of LIMIT. EXPLAIN shows the physical plan.

So in an interview, say "logical order of processing" and mention the optimiser in one line. It shows you know the difference.

Practice questions

Question 1SQL · Order of execution

Which clause is processed first in a query that has SELECT, FROM, WHERE and ORDER BY?

  1. ASELECT
  2. BWHERE
  3. CFROM
  4. DORDER BY
Show answer and explanation

Correct answer: C

FROM (with any joins) comes first, because every later clause needs rows to work on.

Question 2SQL · WHERE vs HAVING

You need customers whose total order value is above 5,000. Where does the condition SUM(amount) > 5000 go?

  1. AWHERE
  2. BHAVING
  3. CORDER BY
  4. DEither WHERE or HAVING
Show answer and explanation

Correct answer: B

It's a condition on a group total, which only exists after GROUP BY, so it goes in HAVING.

Question 3SQL · Aliases

SELECT amount * 2 AS doubled FROM orders ORDER BY doubled; Does this run in PostgreSQL, MySQL and SQL Server?

  1. AYes, ORDER BY runs after SELECT so the alias exists
  2. BNo, aliases can never be used outside SELECT
  3. COnly in MySQL
  4. DOnly if you add GROUP BY
Show answer and explanation

Correct answer: A

ORDER BY is processed after SELECT, so the alias is available in all three.

Where can you practise this?

Order-of-execution mistakes show up most in grouped queries and "top N per group" questions. The 40 SQL interview queries with answers has plenty of both, and second highest salary in SQL works through window functions in detail. For more basics, try the Excel and SQL practice exercises.

If you'd like to learn SQL with a trainer, our SQL training in Anand and live online covers filtering, grouping, joins and window functions with exercises on real datasets. For interview practice on company-style schemas, the SQL interview practice store has question sets with model answers, and ShopX's 10 questions are free.

FAQ

What is the order of execution of a SQL query?

FROM and JOIN, then WHERE, GROUP BY, HAVING, SELECT, DISTINCT, ORDER BY, and finally LIMIT or OFFSET (TOP or FETCH in some databases).

Why can't I use a column alias in the WHERE clause?

Because WHERE is processed before SELECT, where the alias is created. Repeat the expression in WHERE, or wrap the query in a subquery or CTE and filter on the alias outside it.

Is SELECT executed before ORDER BY?

Yes. That's why an alias defined in SELECT can be used in ORDER BY.

What is the difference between WHERE and HAVING?

WHERE filters individual rows before grouping. HAVING filters groups after GROUP BY, so it's where conditions on aggregates like SUM or COUNT go.

When are window functions calculated?

In the SELECT step, after WHERE, GROUP BY and HAVING. To filter on a window function result, calculate it in a CTE or subquery and filter in the outer query.

Choose optional cookies

We use necessary cookies for account security. With your permission, we also use analytics and advertising cookies on marketing pages. See our Privacy Policy.