CTEs and subqueries
Real questions take several steps: total per customer, then keep the big ones, then add their names. CTEs let you write those steps one after another, each with a name, so a long query reads like a recipe.
Foundations · SQL for data engineers · Silver · Structure, sets and dates, lesson 1 of 3
On this page
Read first: Window functions: ranking and top N (skip if you know it)
In plain words first
A query returns a table. So you can use the result of one query as the input of another, just like a table. That is all a subquerysubquery: A query inside another query, in brackets: in FROM as a table, or in WHERE with IN or EXISTS. Learn more → or a CTE is: a query whose result you use as a table.
Take "customers who spent more than 800 in total". You cannot write WHERE sum(amount) > 800, and HAVING works for this one case but not once you need more steps. Instead, compute the totals first, then filter them:
Input: orders
| order_id | customer_id | city | amount | order_date |
|---|---|---|---|---|
| 201 | 1 | Pune | 420 | 2026-03-01 |
| 202 | 2 | Delhi | 650 | 2026-03-01 |
| 203 | 1 | Pune | 300 | 2026-03-02 |
| 204 | 3 | Pune | 540 | 2026-03-02 |
| 205 | 2 | Delhi | 280 | 2026-03-04 |
| 206 | 4 | Pune | 540 | 2026-03-04 |
| 207 | 5 | Mumbai | 390 | 2026-03-05 |
| 208 | 1 | Pune | 180 | 2026-03-05 |
| 209 | 2 | Delhi | 650 | 2026-03-06 |
| 210 | 5 | Mumbai | 210 | 2026-03-06 |
SELECT customer_id, total FROM ( SELECT customer_id, sum(amount) AS total FROM orders GROUP BY customer_id ) AS per_customer WHERE total > 800
Read it from the inside out: the inner query makes a small table of totals, called per_customer, and the outer query filters it. It works, but with three or four steps the nesting becomes hard to follow, because you must read from the middle outwards.
CTEs: name each step
A CTE (common table expression) is the same subquery, moved to the top and given a name with WITH name AS (...). The main query then uses that name like a table. It returns exactly the same rows:
Input: orders
| order_id | customer_id | city | amount | order_date |
|---|---|---|---|---|
| 201 | 1 | Pune | 420 | 2026-03-01 |
| 202 | 2 | Delhi | 650 | 2026-03-01 |
| 203 | 1 | Pune | 300 | 2026-03-02 |
| 204 | 3 | Pune | 540 | 2026-03-02 |
| 205 | 2 | Delhi | 280 | 2026-03-04 |
| 206 | 4 | Pune | 540 | 2026-03-04 |
| 207 | 5 | Mumbai | 390 | 2026-03-05 |
| 208 | 1 | Pune | 180 | 2026-03-05 |
| 209 | 2 | Delhi | 650 | 2026-03-06 |
| 210 | 5 | Mumbai | 210 | 2026-03-06 |
WITH per_customer AS ( SELECT customer_id, sum(amount) AS total FROM orders GROUP BY customer_id ) SELECT customer_id, total FROM per_customer WHERE total > 800
Now it reads top to bottom. Add more steps by separating CTEs with commas. Each one can use the ones above it:
Input: orders
| order_id | customer_id | city | amount | order_date |
|---|---|---|---|---|
| 201 | 1 | Pune | 420 | 2026-03-01 |
| 202 | 2 | Delhi | 650 | 2026-03-01 |
| 203 | 1 | Pune | 300 | 2026-03-02 |
| 204 | 3 | Pune | 540 | 2026-03-02 |
| 205 | 2 | Delhi | 280 | 2026-03-04 |
| 206 | 4 | Pune | 540 | 2026-03-04 |
| 207 | 5 | Mumbai | 390 | 2026-03-05 |
| 208 | 1 | Pune | 180 | 2026-03-05 |
| 209 | 2 | Delhi | 650 | 2026-03-06 |
| 210 | 5 | Mumbai | 210 | 2026-03-06 |
Input: customers
| customer_id | name | city | signup_date |
|---|---|---|---|
| 1 | Asha | Pune | 2026-01-05 |
| 2 | Ravi | Delhi | 2026-01-20 |
| 3 | Meera | Pune | 2026-02-02 |
| 4 | Kabir | Pune | 2026-02-14 |
| 5 | Zoya | Mumbai | 2026-03-01 |
WITH per_customer AS ( SELECT customer_id, sum(amount) AS total FROM orders GROUP BY customer_id ), with_names AS ( SELECT c.name, c.city, p.total FROM per_customer p JOIN customers c ON c.customer_id = p.customer_id ) SELECT city, name, total FROM with_names ORDER BY total DESC
SELECT * FROM per_customer, check it, then move on to the next CTE. Almost every wrong answer shows up as a step with too many or too few rows.Scalar subqueries: one value
A subquery that returns exactly one row and one column can be used anywhere a single value can, such as in WHERE or SELECT:
Input: orders
| order_id | customer_id | city | amount | order_date |
|---|---|---|---|---|
| 201 | 1 | Pune | 420 | 2026-03-01 |
| 202 | 2 | Delhi | 650 | 2026-03-01 |
| 203 | 1 | Pune | 300 | 2026-03-02 |
| 204 | 3 | Pune | 540 | 2026-03-02 |
| 205 | 2 | Delhi | 280 | 2026-03-04 |
| 206 | 4 | Pune | 540 | 2026-03-04 |
| 207 | 5 | Mumbai | 390 | 2026-03-05 |
| 208 | 1 | Pune | 180 | 2026-03-05 |
| 209 | 2 | Delhi | 650 | 2026-03-06 |
| 210 | 5 | Mumbai | 210 | 2026-03-06 |
SELECT order_id, amount FROM orders WHERE amount > (SELECT avg(amount) FROM orders) ORDER BY amount DESC
The average is 416, so five orders qualify. If a scalar subquery returns more than one row, the query fails, so make sure it is an aggregateaggregate: A function that turns many rows into one value: count, sum, avg, min, max. With GROUP BY it gives one value per group. Learn more → or is filtered to one row.
Correlated subqueries: one value per row
A correlatedcorrelated subquery: A subquery that refers to a column of the outer query, so it is checked once for each outer row. Learn more → subquery uses a column of the outer query, so its answer is different for each outer row. "Orders above their own city's average":
Input: orders
| order_id | customer_id | city | amount | order_date |
|---|---|---|---|---|
| 201 | 1 | Pune | 420 | 2026-03-01 |
| 202 | 2 | Delhi | 650 | 2026-03-01 |
| 203 | 1 | Pune | 300 | 2026-03-02 |
| 204 | 3 | Pune | 540 | 2026-03-02 |
| 205 | 2 | Delhi | 280 | 2026-03-04 |
| 206 | 4 | Pune | 540 | 2026-03-04 |
| 207 | 5 | Mumbai | 390 | 2026-03-05 |
| 208 | 1 | Pune | 180 | 2026-03-05 |
| 209 | 2 | Delhi | 650 | 2026-03-06 |
| 210 | 5 | Mumbai | 210 | 2026-03-06 |
SELECT o.order_id, o.city, o.amount FROM orders o WHERE o.amount > ( SELECT avg(i.amount) FROM orders i WHERE i.city = o.city ) ORDER BY o.city, o.order_id
For Delhi the inner query averages Delhi orders (526.7), for Pune it averages Pune orders (396). The aliasesalias: A short name given with AS (or just a space) to a table or column, like orders o or amount + 25 AS total. Learn more → o (outer) and i (inner) are what make this readable. A window functionwindow function: A function computed over a group of rows, written with OVER (...), that keeps every row instead of collapsing them like GROUP BY. Learn more → does the same in one pass, and is usually how you would write it in Spark:
Input: orders
| order_id | customer_id | city | amount | order_date |
|---|---|---|---|---|
| 201 | 1 | Pune | 420 | 2026-03-01 |
| 202 | 2 | Delhi | 650 | 2026-03-01 |
| 203 | 1 | Pune | 300 | 2026-03-02 |
| 204 | 3 | Pune | 540 | 2026-03-02 |
| 205 | 2 | Delhi | 280 | 2026-03-04 |
| 206 | 4 | Pune | 540 | 2026-03-04 |
| 207 | 5 | Mumbai | 390 | 2026-03-05 |
| 208 | 1 | Pune | 180 | 2026-03-05 |
| 209 | 2 | Delhi | 650 | 2026-03-06 |
| 210 | 5 | Mumbai | 210 | 2026-03-06 |
WITH with_avg AS ( SELECT order_id, city, amount, avg(amount) OVER (PARTITION BY city) AS city_avg FROM orders ) SELECT order_id, city, amount FROM with_avg WHERE amount > city_avg ORDER BY city, order_id
Which one to use
| Form | Good for | Watch out |
|---|---|---|
| CTE | Any query with more than one step; the default choice | Spark does not store a CTE: one used twice may be computed twice |
| Subquery in FROM | A single short step | Deep nesting is hard to read; switch to CTEs |
| Scalar subquery | One number to compare with, like an overall average | Must return one row |
| IN / EXISTS subquery | Keep rows that have a match (the semi and anti joinsanti join: A join that keeps the left rows that have no match at all on the right. Learn more → lesson) | NOT IN with NULLsNULL: A missing or unknown value. It is not 0 or an empty string, and any comparison with it is unknown instead of true or false. Learn more → returns nothing |
| Correlated subquery | Small per-row checks | A window function or join is often simpler and faster |
A CTE is not a saved table. It is only a name for a step of this one query, and it disappears when the query ends. If several queries need the same step, make it a view or a table.
Common mistakes
- Nesting subqueries three deep — Readers must start in the middle. Rewrite as CTEs that read top to bottom.
- A scalar subquery that returns several rows — The query fails at run time. Aggregate, or filter it to exactly one row.
- Expecting a CTE to be computed once — Spark may run a CTE once per place it is used. For an expensive step used often, write it to a table.
- Leaving a comma before the main SELECT — CTEs are separated by commas, but the last one is followed directly by SELECT. A trailing comma is a syntax error.
Key takeaways
- A subquery or CTE is a query whose result you use as a table.
- WITH name AS (...) names a step; separate several with commas; each can use the ones above.
- CTEs read top to bottom; nested subqueries read inside out.
- A scalar subquery returns one value; a correlated one is re-evaluated for each outer row.
- Check a long query one CTE at a time.
Interview prep
THE QUESTION
"Find customers whose total spend is above the average customer's total spend."
WITH per_customer AS (SELECT customer_id, sum(amount) AS total FROM orders GROUP BY customer_id), then SELECT * FROM per_customer WHERE total > (SELECT avg(total) FROM per_customer). The point to say out loud is that the average must be of the per-customer totals, not of the order amounts: averaging orders gives a different, smaller number. A window version, avg(total) OVER () in a second CTE, is equally fine.Avoid: Averaging the order amounts instead of the per-customer totals. WHERE total > (SELECT avg(amount) FROM orders) compares a customer's total with the size of an average order, which is a much smaller number, so almost everyone passes.
Follow-ups · answer out loud, then open
Follow-up"Is a CTE faster than the same subquery?"
Scenario"A 200-line query returns too many rows. How do you debug it?"
SELECT count(*) FROM step_n, and find the first step whose row count jumps: almost always a join that fans out on a key that is not unique. Then check that key with a GROUP BY ... HAVING count(*) > 1.Trap"Rewrite WHERE amount > (SELECT avg(amount) FROM orders i WHERE i.city = o.city) without a subquery."
avg(amount) OVER (PARTITION BY city) in a CTE, then filter in the outer query. Or join to a per-city average CTE. Both read the table without a per-row lookup, and the window version reads it once.Check yourself
4 questionsWhat does WITH t AS (SELECT ...) create?
Show the answer
A name for a step, usable only in this query. A CTE exists only for the query it belongs to.
A subquery in WHERE uses a column of the outer query. It is called...
Show the answer
Correlated. It depends on the outer row, so its value changes per row.
What happens if WHERE amount > (SELECT amount FROM orders) runs on a table of 10 rows?
Show the answer
It fails: the subquery returns more than one row. A scalar subquery must return a single row.
How are two CTEs in one WITH separated?
Show the answer
A comma. WITH a AS (...), b AS (...) SELECT ...
Practise this
Problems that use this, graded on hidden tests
Keep going
Up next · Structure, sets and dates · lesson 2 of 3 · 6 min readUNION, INTERSECT and EXCEPT
Stack, intersect and subtract query results, the rules they follow, and reconciling two sources.
Related lessons
Window functions: ranking and top NSQL for data engineers · 7 min read
Semi and anti joins
Previous: Running totals and window frames
Primary sources: Common table expressions · Subqueries