Skip to content
Silver 6 min read · Structure 3 practice problems ↓

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

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:

Spark SQL · A subquery in FROM

Input: orders

order_idcustomer_idcityamountorder_date
2011Pune4202026-03-01
2022Delhi6502026-03-01
2031Pune3002026-03-02
2043Pune5402026-03-02
2052Delhi2802026-03-04
2064Pune5402026-03-04
2075Mumbai3902026-03-05
2081Pune1802026-03-05
2092Delhi6502026-03-06
2105Mumbai2102026-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:

Spark SQL · The same query as a CTE

Input: orders

order_idcustomer_idcityamountorder_date
2011Pune4202026-03-01
2022Delhi6502026-03-01
2031Pune3002026-03-02
2043Pune5402026-03-02
2052Delhi2802026-03-04
2064Pune5402026-03-04
2075Mumbai3902026-03-05
2081Pune1802026-03-05
2092Delhi6502026-03-06
2105Mumbai2102026-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:

Spark SQL · Two steps: totals, then names

Input: orders

order_idcustomer_idcityamountorder_date
2011Pune4202026-03-01
2022Delhi6502026-03-01
2031Pune3002026-03-02
2043Pune5402026-03-02
2052Delhi2802026-03-04
2064Pune5402026-03-04
2075Mumbai3902026-03-05
2081Pune1802026-03-05
2092Delhi6502026-03-06
2105Mumbai2102026-03-06

Input: customers

customer_idnamecitysignup_date
1AshaPune2026-01-05
2RaviDelhi2026-01-20
3MeeraPune2026-02-02
4KabirPune2026-02-14
5ZoyaMumbai2026-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
Debugging a long query: Run one step at a time: replace the final SELECT with 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:

Spark SQL · Orders above the overall average

Input: orders

order_idcustomer_idcityamountorder_date
2011Pune4202026-03-01
2022Delhi6502026-03-01
2031Pune3002026-03-02
2043Pune5402026-03-02
2052Delhi2802026-03-04
2064Pune5402026-03-04
2075Mumbai3902026-03-05
2081Pune1802026-03-05
2092Delhi6502026-03-06
2105Mumbai2102026-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":

Spark SQL · Compare each order with its own city

Input: orders

order_idcustomer_idcityamountorder_date
2011Pune4202026-03-01
2022Delhi6502026-03-01
2031Pune3002026-03-02
2043Pune5402026-03-02
2052Delhi2802026-03-04
2064Pune5402026-03-04
2075Mumbai3902026-03-05
2081Pune1802026-03-05
2092Delhi6502026-03-06
2105Mumbai2102026-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:

Spark SQL · The same with a window function

Input: orders

order_idcustomer_idcityamountorder_date
2011Pune4202026-03-01
2022Delhi6502026-03-01
2031Pune3002026-03-02
2043Pune5402026-03-02
2052Delhi2802026-03-04
2064Pune5402026-03-04
2075Mumbai3902026-03-05
2081Pune1802026-03-05
2092Delhi6502026-03-06
2105Mumbai2102026-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

FormGood forWatch out
CTEAny query with more than one step; the default choiceSpark does not store a CTE: one used twice may be computed twice
Subquery in FROMA single short stepDeep nesting is hard to read; switch to CTEs
Scalar subqueryOne number to compare with, like an overall averageMust return one row
IN / EXISTS subqueryKeep 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 subquerySmall per-row checksA 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."

Two steps, so two CTEs: 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?"
No, in Spark they compile to the same plan: a CTE is a name, not a stored result. A CTE referenced twice may even be computed twice. It is about readability; for real reuse of an expensive step, write it to a table or cache it.
Scenario"A 200-line query returns too many rows. How do you debug it?"
If it is written as CTEs, run them one at a time, 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."
A window function: 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 questions

What 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 read
UNION, INTERSECT and EXCEPT
Stack, intersect and subtract query results, the rules they follow, and reconciling two sources.

Related lessons

Previous: Running totals and window frames

Primary sources: Common table expressions · Subqueries