Lesson 217 of 296
Subqueries and CTEs
What you will learn
- Subqueries in WHERE, FROM and SELECT
- EXISTS and NOT EXISTS
- The NOT IN and NULL trap
- Correlated subqueries
- Common Table Expressions (WITH)
- Recursive CTEs
On this page
Subqueries
A subquery is a query inside another query, in brackets.
In WHERE (a single value): products more expensive than the average:
SELECT name, price_pence FROM products
WHERE price_pence > (SELECT AVG(price_pence) FROM products)
ORDER BY price_pence;| name | price_pence |
|---|---|
| Desk Lamp | 2999 |
| Kettle | 3499 |
(The average is 1819.4 pence.) You cannot write WHERE price_pence > AVG(price_pence) directly: aggregates are not allowed in WHERE.
In FROM (a derived table): a subquery used as a temporary table; it must have an alias. See the "latest order per customer" example in Lesson 218.
In SELECT (a scalar subquery): returns one value per row, e.g. (SELECT COUNT(*) FROM orders o WHERE o.customer_id = c.id) AS order_count. Easy to write but runs per row; a join with GROUP BY is often faster.
EXISTS and NOT EXISTS
EXISTS (subquery) is true if the subquery returns at least one row:
SELECT name FROM customers c
WHERE EXISTS (
SELECT 1 FROM orders o WHERE o.customer_id = c.id AND o.status = 'paid'
)
ORDER BY name;| name |
|---|
| Aisha Khan |
| Chen Li |
This is a correlated subquery: it refers to c from the outer query, so conceptually it runs for each customer (the database usually optimises it into a join). NOT EXISTS finds customers with no paid orders. SELECT 1 is a convention: EXISTS only checks whether rows exist, not what they contain.
The NOT IN trap
SELECT name FROM customers WHERE id NOT IN (SELECT customer_id FROM orders);| name |
|---|
| Eve Jones |
That works here. But if the subquery can return a NULL, NOT IN returns no rows at all:
SELECT name FROM customers WHERE city NOT IN ('Leeds', NULL);This returns nothing. x NOT IN (a, NULL) means x <> a AND x <> NULL, and x <> NULL is unknown, so no row passes. Prefer NOT EXISTS (or the LEFT JOIN anti-join), which handles NULLs correctly. A classic senior interview trap.
Common Table Expressions (CTEs)
A CTE names a subquery with WITH, so complex queries read top to bottom like steps:
WITH order_totals AS (
SELECT o.id, o.customer_id, o.ordered_at,
SUM(oi.quantity * oi.unit_price_pence) AS total_pence
FROM orders o
JOIN order_items oi ON oi.order_id = o.id
WHERE o.status = 'paid'
GROUP BY o.id
)
SELECT c.name, COUNT(*) AS paid_orders, ROUND(AVG(t.total_pence)) AS avg_order_pence
FROM order_totals t
JOIN customers c ON c.id = t.customer_id
GROUP BY c.id, c.name
ORDER BY avg_order_pence DESC;| name | paid_orders | avg_order_pence |
|---|---|---|
| Chen Li | 2 | 3649 |
| Aisha Khan | 2 | 2624 |
Step 1 computes each order's total; step 2 averages the totals per customer. Doing it in one step would be wrong: averaging item rows is not the same as averaging order totals. CTEs also solve the fan-out problem (Lesson 215): aggregate each relationship in its own CTE, then join the results.
- You can define several CTEs:
WITH a AS (...), b AS (...) SELECT .... - Since PostgreSQL 12, simple CTEs are inlined by the optimiser, so they are usually as fast as subqueries.
AS MATERIALIZEDforces the result to be computed once and stored.
Recursive CTEs
A recursive CTE refers to itself: perfect for hierarchies (categories with sub-categories, an organisation chart, comment threads):
WITH RECURSIVE chain AS (
SELECT id, name, manager_id, 1 AS depth FROM employees WHERE id = 42 the starting row
UNION ALL
SELECT e.id, e.name, e.manager_id, chain.depth + 1
FROM employees e JOIN chain ON e.id = chain.manager_id one level up each time
)
SELECT * FROM chain;This walks from employee 42 up to the top of the management chain. The first part is the anchor; the second part repeats until it returns no new rows.
UNION, INTERSECT, EXCEPT
Combine results of queries with the same columns:
| Operator | Result |
|---|---|
UNION | Rows from either, duplicates removed (slower: needs de-duplication) |
UNION ALL | Rows from either, duplicates kept (faster; use when duplicates are impossible or wanted) |
INTERSECT | Rows in both |
EXCEPT | Rows in the first but not the second |
How to say it in an interview
"Subqueries can return a single value for WHERE, act as derived tables in FROM, or compute per-row values in SELECT. EXISTS checks whether a correlated subquery returns any row, and I prefer NOT EXISTS over NOT IN because a single NULL in the NOT IN list makes the whole condition unknown and returns nothing. CTEs with WITH name intermediate steps, make complex queries readable, and let me aggregate before joining to avoid fan-out; recursive CTEs walk hierarchies like org charts. UNION removes duplicates while UNION ALL keeps them and is faster."
Key words
| Word | Meaning |
|---|---|
| Subquery | A query inside another query |
| Derived table | A subquery in FROM used as a table |
| Correlated subquery | A subquery that refers to the outer query |
| EXISTS | True if a subquery returns any row |
| CTE | A named subquery defined with WITH |
| Recursive CTE | A CTE that refers to itself, for hierarchies |
| UNION vs UNION ALL | Combine results removing vs keeping duplicates |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.