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.
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,WHEREorORDER BY. - A set subquery returns one column of many rows, used with
IN,NOT INorEXISTS. - A derived table returns a whole table and sits in
FROM, where you join or select from it like any table.
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 expressionSQLite does not complain. It quietly uses the first row it finds:
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:
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.
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 INwith a subquery, addWHERE col IS NOT NULLinside it. NOT INwith a literal list you control, likestatus NOT IN ('cancelled', 'pending'), is fine.
DELETE FROM users WHERE id NOT IN (SELECT user_id FROM sessions). One session row has user_id NULL. What happens?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:
Press Run (⌘ Enter) to see what happens.live_orders keeps only paid and shipped orders. One decision, made once, with a name a reviewer can check.
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_customerabove. 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.
WHERE customer_id = 42. What does the planner do?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 ALLappends the second result to the first. It keeps every row.UNIONdoes the same and then removes duplicate rows, which costs a sort or a hash over the whole result.INTERSECTkeeps rows that appear in both.EXCEPTkeeps rows from the first that are not in the second.
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.
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])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 want | Reach for | Why |
|---|---|---|
| Columns from both tables | JOIN | Only a join puts columns side by side |
| Rows that have a match, no extra columns | EXISTS or IN | No fan-out, so no duplicates to remove |
| Rows that have no match | NOT EXISTS | NULL-safe and becomes an anti-join |
| A value computed from another table, per row | Join to a grouped derived table or CTE | Avoids a per-row SubPlan on big tables |
| A multi-step calculation | A chain of CTEs | Each step named, testable on its own |
| Rows from two queries, stacked | UNION ALL | No 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 each task to the operation that does it.
- 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.