Skip to content

Lesson 8 of 29Joining and aggregating

Subqueries, CTEs and Set Operations

Nest queries inside queries, name each step with WITH, combine results with UNION, INTERSECT and EXCEPT, and dodge the NOT IN NULL trap.

18 min read0/4 questions

Sooner or later a question needs more than one step. "Which customers spent more than the average customer?" needs the average first. "What share of revenue came from each customer, counting only paid and shipped orders?" needs three steps before the answer. You can write that as one 60-line query with brackets nested four deep, and nobody on your team will be able to review it. Or you can name each step with a CTE so it reads top to bottom like a recipe. This lesson covers every place a query can go inside another query, how the database actually runs them, the set operations that glue results together, and one NULL trap that has deleted the wrong rows in more than one company.

Three places a subquery can go

A subquery is a SELECT in brackets inside another statement. What it is allowed to return depends on where you put it:

  • A scalar subquery returns one column and at most one row, and you can use it anywhere a single value fits: in SELECT, WHERE or ORDER BY.
  • A set subquery returns one column of many rows, used with IN, NOT IN or EXISTS.
  • A derived table returns a whole table and sits in FROM, where you join or select from it like any table.
Python
from shopdb import connect, showdb = connect()# Scalar: one value, used twiceshow(db, """SELECT name, price_cents, (SELECT AVG(price_cents) FROM products) AS avg_priceFROM productsWHERE price_cents > (SELECT AVG(price_cents) FROM products)ORDER BY price_cents DESC""")# Set: a list of ids for INshow(db, """SELECT name FROM customersWHERE id IN (SELECT customer_id FROM orders WHERE status = 'pending')ORDER BY name""")# Derived table: totals per order, then an average over themshow(db, """SELECT t.status, AVG(t.total_cents) AS avg_order_centsFROM ( SELECT o.id, o.status, SUM(oi.quantity * oi.unit_price_cents) AS total_cents FROM orders o JOIN order_items oi ON oi.order_id = o.id GROUP BY o.id, o.status) AS tGROUP BY t.statusORDER BY avg_order_cents DESC""")
Output
Press Run (⌘ Enter) to see what happens.

The third query is the "aggregate first, then aggregate again" pattern you met in Aggregation, GROUP BY and HAVING. You cannot write AVG(SUM(...)) directly, because aggregates do not nest. A derived table produces one row per order, and the outer query averages those rows.

Give every derived table an alias. Postgres required one until version 16, MySQL still does ("Every derived table must have its own alias"), and a name makes the outer query readable anyway.

Scalar subqueries must return one row

A scalar subquery that returns zero rows gives NULL. One that returns two or more rows is an error in Postgres:

SELECT name,
       (SELECT id FROM orders WHERE orders.customer_id = customers.id) AS an_order
FROM customers;
-- ERROR:  more than one row returned by a subquery used as an expression

SQLite does not complain. It quietly uses the first row it finds:

Python
from shopdb import connect, showdb = connect()# Postgres raises an error here. SQLite takes the first row it finds.show(db, """SELECT name, (SELECT id FROM orders WHERE orders.customer_id = customers.id) AS an_orderFROM customersORDER BY id""")
Output
Press Run (⌘ Enter) to see what happens.

Ada has three orders, and SQLite shows one of them with no warning. Worse, the Postgres version often works in development, where every test customer has one order, and fails in production on the first customer with two. When a scalar subquery could match several rows, decide which one you want and say it: MAX(id), or ORDER BY created_at DESC LIMIT 1.

Correlated subqueries

The subquery above mentions customers.id, a column from the outer query. That makes it a correlated subquery: logically, it runs once for every outer row, with that row's values plugged in. "Products priced above their own category's average" is the classic case:

Python
from shopdb import connect, showdb = connect()show(db, """SELECT p.name, p.category_id, p.price_centsFROM products pWHERE p.price_cents > ( SELECT AVG(p2.price_cents) FROM products p2 WHERE p2.category_id = p.category_id)ORDER BY p.category_id""")
Output
Press Run (⌘ Enter) to see what happens.

"Runs once per row" describes the meaning, not necessarily the execution. Planners rewrite a lot of correlated subqueries into joins, which is called decorrelation. Postgres turns EXISTS and IN in a WHERE clause into semi-joins and anti-joins, so they run as efficiently as a hand-written join. A correlated scalar subquery in the SELECT list is a different story: Postgres usually runs it as a SubPlan, once per outer row. On 50 rows that is nothing. On 5 million rows with no index on the inner column, it is a query that never finishes. When you see SubPlan in EXPLAIN on a large table, try rewriting it as a join to a grouped derived table. Reading EXPLAIN and EXPLAIN ANALYZE covers the plan nodes in detail.

EXISTS, IN and NOT IN with subqueries

EXISTS (subquery) is true if the subquery returns at least one row. It does not care what the row contains, which is why you see SELECT 1 inside it, and it can stop at the first match. IN (subquery) asks whether a value appears in the subquery's column. For the positive case they give the same answer, and Postgres plans both as a semi-join: each outer row is returned once, however many matches it has.

Python
from shopdb import connect, showdb = connect()# Customers with at least one order over 1,000.00, two waysshow(db, """SELECT name FROM customers cWHERE EXISTS ( SELECT 1 FROM orders o JOIN order_items oi ON oi.order_id = o.id WHERE o.customer_id = c.id GROUP BY o.id HAVING SUM(oi.quantity * oi.unit_price_cents) > 100000)ORDER BY name""")show(db, """SELECT name FROM customersWHERE id IN ( SELECT o.customer_id FROM orders o JOIN order_items oi ON oi.order_id = o.id GROUP BY o.id, o.customer_id HAVING SUM(oi.quantity * oi.unit_price_cents) > 100000)ORDER BY name""")
Output
Press Run (⌘ Enter) to see what happens.

The negative case is where they differ. You saw the NOT IN trap in NULL and Three-Valued Logic: if the subquery's column contains a single NULL, x NOT IN (subquery) is never TRUE and the query returns nothing. Inside a SELECT that gives an empty report. Inside a cleanup job it is worse, because the job reports success while doing nothing, and nobody notices for months.

There is also a performance reason to prefer NOT EXISTS. Because of that NULL rule, Postgres has historically been unable to plan NOT IN (subquery) as an anti-join. It runs it as a SubPlan, hashed if the subquery result fits in memory and row by row if it does not, which on large tables can be orders of magnitude slower than the NOT EXISTS version. So the rules are:

  • For "no matching row in another table", use NOT EXISTS. It is NULL-safe and becomes an anti-join.
  • If you keep NOT IN with a subquery, add WHERE col IS NOT NULL inside it.
  • NOT IN with a literal list you control, like status NOT IN ('cancelled', 'pending'), is fine.
Quick check
A cleanup job runs DELETE FROM users WHERE id NOT IN (SELECT user_id FROM sessions). One session row has user_id NULL. What happens?
Need a nudge? A hint rules out a wrong answer.

CTEs: name your steps

A common table expression (CTE) is a named subquery written before the main query with WITH name AS (...). Later CTEs and the main query can refer to it by name. It changes nothing about what you can express; it changes how readable the query is, a lot.

Here is the revenue-share question from the introduction, in four named steps:

Python
from shopdb import connect, showdb = connect()show(db, """WITH live_orders AS ( SELECT id, customer_id FROM orders WHERE status IN ('paid', 'shipped')),order_totals AS ( SELECT lo.id, lo.customer_id, SUM(oi.quantity * oi.unit_price_cents) AS total_cents FROM live_orders lo JOIN order_items oi ON oi.order_id = lo.id GROUP BY lo.id, lo.customer_id),per_customer AS ( SELECT customer_id, COUNT(*) AS orders, SUM(total_cents) AS spent_cents FROM order_totals GROUP BY customer_id)SELECT c.name, pc.orders, pc.spent_cents, ROUND(100.0 * pc.spent_cents / (SELECT SUM(spent_cents) FROM per_customer), 1) AS pctFROM per_customer pcJOIN customers c ON c.id = pc.customer_idORDER BY pc.spent_cents DESC""")
Output
Press Run (⌘ Enter) to see what happens.
A chain of CTEs, one idea per step
orders: 10 rowsorders10 rowsorder_items: 17 rowsorder_items17 rowslive_orders: 7 paid or shippedlive_orders7 paid or shippedorder_totals: 1 row per orderorder_totals1 row per orderper_customer: 1 row per customerper_customer1 row per customerfinal SELECT: names and sharesfinal SELECTnames and sharesfilterjoinjoingroupjoin customers

live_orders keeps only paid and shipped orders. One decision, made once, with a name a reviewer can check.

1/4

Each CTE has one job and a name that says what one row means. That is the habit that makes analytics SQL reviewable: when a number looks wrong, you can run each step on its own (SELECT * FROM order_totals) and see where it went off. Two further benefits:

  • A CTE can be referenced more than once, like per_customer above. With derived tables you would copy the whole subquery.
  • CTEs can be recursive, which lets SQL walk trees and graphs. That is the whole next lesson, Recursive CTEs and Hierarchies.

A CTE exists only for the statement it belongs to. It is not a temporary table and it is not saved anywhere. If several queries need the same step, that is a job for a view.

Are CTEs optimisation fences?

You will find blog posts saying "never use CTEs in Postgres, they block the optimiser". That was true before Postgres 12: every CTE was computed in full and stored, so a filter in the outer query could not be pushed down into it. A CTE that read a 100-million-row table read all of it, even when the outer query needed 10 rows.

Since Postgres 12, a CTE that is not recursive, has no side effects and is referenced once is inlined: the planner treats it exactly like a subquery and optimises across the boundary. A CTE referenced two or more times is still materialised by default, because computing it once is usually cheaper. You can override either choice:

WITH recent AS MATERIALIZED (       -- compute once, store, reuse
  SELECT * FROM events WHERE created_at > now() - interval '1 day'
)
SELECT ...;
 
WITH per_customer AS NOT MATERIALIZED (   -- inline even if used twice
  SELECT ...
)
SELECT ...;

MATERIALIZED is still useful as a deliberate fence, for example to stop the planner from choosing a bad plan by merging a step it misestimates. Use it when EXPLAIN shows you a reason, not by default. SQLite accepts the same two hints. If you are on a Postgres older than 12 (some legacy systems are), the old advice still applies there.

Quick check
On Postgres 18, a CTE that filters a large table is referenced once in the main query, which adds WHERE customer_id = 42. What does the planner do?
Need a nudge? A hint rules out a wrong answer.

Set operations: UNION, INTERSECT and EXCEPT

Joins put tables side by side. Set operations stack query results on top of each other. Both queries must return the same number of columns with compatible types; the column names come from the first query, and one ORDER BY at the end sorts the combined result.

  • UNION ALL appends the second result to the first. It keeps every row.
  • UNION does the same and then removes duplicate rows, which costs a sort or a hash over the whole result.
  • INTERSECT keeps rows that appear in both. EXCEPT keeps rows from the first that are not in the second.
Python
from shopdb import connect, showdb = connect()print("Viewed a product but never checked out")show(db, """SELECT user_id FROM events WHERE kind = 'view_product'EXCEPTSELECT user_id FROM events WHERE kind = 'checkout'""")print()print("Added to cart AND checked out")show(db, """SELECT user_id FROM events WHERE kind = 'add_to_cart'INTERSECTSELECT user_id FROM events WHERE kind = 'checkout'""")print()show(db, """SELECT (SELECT COUNT(*) FROM (SELECT user_id FROM events WHERE kind = 'login' UNION ALL SELECT customer_id FROM orders)) AS union_all_rows, (SELECT COUNT(*) FROM (SELECT user_id FROM events WHERE kind = 'login' UNION SELECT customer_id FROM orders)) AS union_rows""")
Output
Press Run (⌘ Enter) to see what happens.

Default to UNION ALL. Most of the time you are stacking results you know are disjoint (this month's table and last month's archive), and UNION makes the database deduplicate millions of rows for nothing. Reach for UNION only when you actually want duplicates removed, and then say so in a comment, because a reviewer cannot tell an intentional UNION from a careless one.

Set operations compare whole rows, and for this purpose NULLs count as equal to each other. That is different from = in a WHERE clause. EXCEPT is also a handy testing tool: (old_query EXCEPT new_query) UNION ALL (new_query EXCEPT old_query) returns nothing when a rewritten query gives the same rows as the old one.

Predict the outputPython

What does this print?

from shopdb import connect
db = connect()
# The customers table has 8 rows. Cities: London (twice), New York,
# Hampton, Portland, Geneva, Boston, and one NULL.
print(db.execute("""
SELECT COUNT(*) FROM (
SELECT city FROM customers
UNION
SELECT city FROM customers
)
""").fetchone()[0])
Need a nudge? Hints walk you through it.

Join, EXISTS, IN or CTE?

Several of these tools answer the same question. Pick in this order: what is correct, then what reads clearly, then what EXPLAIN says is fast.

You wantReach forWhy
Columns from both tablesJOINOnly a join puts columns side by side
Rows that have a match, no extra columnsEXISTS or INNo fan-out, so no duplicates to remove
Rows that have no matchNOT EXISTSNULL-safe and becomes an anti-join
A value computed from another table, per rowJoin to a grouped derived table or CTEAvoids a per-row SubPlan on big tables
A multi-step calculationA chain of CTEsEach step named, testable on its own
Rows from two queries, stackedUNION ALLNo dedup cost

A common review comment is "use a join instead of IN, it's faster". In modern Postgres, IN (subquery) and EXISTS are planned as semi-joins, usually with the same plan as the equivalent join plus DISTINCT. The real difference is semantic: a join can duplicate parent rows when there are several matches, and a semi-join never does.

Writable CTEs in Postgres

Postgres lets a CTE contain INSERT, UPDATE or DELETE with RETURNING, and the rest of the statement can use the returned rows. The classic use is archiving: move old rows to another table in one atomic statement.

WITH moved AS (
  DELETE FROM events
  WHERE created_at < now() - interval '90 days'
  RETURNING *
)
INSERT INTO events_archive
SELECT * FROM moved;

Either both parts happen or neither does, with no window where a row exists in both tables or in neither. Two rules to know: every part of the statement sees the same snapshot of the data from before the statement started, so the main query cannot see the CTE's changes except through RETURNING; and the order in which sub-statements run is not defined, so do not modify the same row twice in one statement. For millions of rows, run it in batches (add a LIMIT through a subquery on the key) so one huge transaction does not hold locks and bloat the table. SQLite and MySQL do not allow data-modifying statements inside a CTE.

Match the pairs0/5 matched

Match each task to the operation that does it.

Choose an item, then its match on the other side.
Key terms
scalar subquery
A subquery that returns one value. Zero rows give NULL; more than one row is an error in Postgres.
derived table
A subquery in the FROM clause, used like a table. Give it an alias.
correlated subquery
A subquery that refers to columns of the outer query, so logically it runs once per outer row.
decorrelation
The planner rewriting a correlated subquery as a join, such as turning EXISTS into a semi-join.
CTE
A common table expression: a named subquery written with WITH, visible only within its statement.
materialisation
Computing a CTE once and storing its rows. Postgres 12+ only does it by default when the CTE is used more than once.
anti-join
A join that keeps rows with no match on the other side, which is how NOT EXISTS runs.