Skip to content
Commitwise
Menu
Databases

Subqueries and CTEs

Queries inside queries, correlated subqueries that run once per row, WITH clauses that name each step, a CTE the main query forgot to use, moving rows in one statement, and recursive CTEs for category trees and referral chains, including the one that never ends.

intermediate

The core idea with one simple example.Step by step, with more examples and exercises.A cheat sheet: key APIs, gotchas and trade-offs.Internals, trade-offs and production pitfalls.

“Products priced above average” sounds like one query, but it’s two: first the average, then the products. “Customers who spend more than the average customer” is three. “Every subcategory of Electronics, however deep” can’t be written with a fixed number of joins at all.

Subqueries and CTEs (the WITH clause) let one SQL statement do several steps. They turn the long, unreadable queries you inherit into a list of named steps, and recursive CTEs walk trees and graphs that plain joins can’t. The examples use the shop tables from How relational databases work.

New to some of these? Open what you need, or skip ahead.

Basics:GROUP BY and aggregates

count, sum, avg, min and max turn many rows into one value; GROUP BY gives one row per group; HAVING filters groups. WHERE runs before grouping, so it can’t use avg(…). See Aggregation.

Basics:JOIN

A join puts rows from two tables side by side, matching them with ON, usually foreign key = primary key: FROM orders o JOIN customers c ON c.id = o.customer_id. An inner join returns one row per match. See Joins.

Part Not started

Queries inside queries

“Products that cost more than the average product.” You might try WHERE price > avg(price), but aggregates aren’t allowed in WHERE: it runs on single rows, before anything is averaged.

Instead, put a whole query in parentheses where the value should go. That’s a subquery. The database runs it first and uses its result:

SELECT name, price
FROM products
WHERE price > (SELECT avg(price) FROM products);

Subqueries can go in four places:

WhereIt returnsExample
WHERE x > (…) or in SELECTone valueabove the average price
WHERE x IN (…)a list of valuescustomers who ordered this week
FROM (…) AS namea table, which needs a nametotals per customer, then filtered
WHERE EXISTS (…)true or falseproducts that were ever ordered

A subquery can also refer to the outer row. This one runs once for each customer, using that customer’s c.id:

SELECT c.name,
       (SELECT count(*) FROM orders o WHERE o.customer_id = c.id) AS orders
FROM customers c;

That’s called a correlated subqueryCorrelated subqueryA subquery that refers to a column of the outer query, so it is evaluated once per outer row.Open in glossary →. It’s easy to read, but “once per row” can be slow on big tables; a join with GROUP BY usually does the same work in one pass.

  • Kinds: scalar (one row, one column; zero rows give NULL, two rows are a runtime error), row, table (derived table, needs an alias except in PostgreSQL 16+), and predicate subqueries (IN, EXISTS, ANY/ALL).
  • Correlated vs uncorrelated: uncorrelated ones run once (an InitPlan in PostgreSQL’s EXPLAIN). Correlated ones are evaluated per outer row (a SubPlan) unless the planner rewrites them: EXISTS/IN become semi- and anti-joins, but scalar subqueries in the SELECT list are generally not decorrelated by PostgreSQL. With an index on the inner column it’s an index probe per row, fine for a page of 50, painful for a report over a million rows.
  • Rewrites: per-row aggregates → join to a grouped derived table, or LEFT JOIN LATERAL for top-N per row. “Above the group average” → window function avg() OVER (PARTITION BY …).
  • IN vs EXISTS: equivalent for semi-joins in modern planners; the real difference is NOT IN with NULLs (it returns nothing). = ANY (array) is PostgreSQL’s way to bind a list as one parameter: WHERE id = ANY($1).
  • Readability: deeply nested derived tables read inside-out. Move steps into CTEs.

Predict the output

Ana has two orders; Ben has none. What does this query do?

SELECT c.name,
       (SELECT o.id FROM orders o WHERE o.customer_id = c.id) AS order_id
FROM customers c
WHERE c.name IN ('Ana', 'Ben');
-- customers who ordered in the last 7 days
SELECT id, name FROM customers
WHERE id IN (SELECT customer_id FROM orders WHERE created_at >= now() - interval '7 days');

-- products that were never ordered
SELECT id, name FROM products p
WHERE NOT EXISTS (SELECT 1 FROM order_items oi WHERE oi.product_id = p.id);

-- a derived table: customers who spent more than 500, from a grouped subquery
SELECT c.name, t.spent
FROM (SELECT customer_id, sum(total) AS spent
      FROM orders WHERE status = 'PAID'
      GROUP BY customer_id) AS t
JOIN customers c ON c.id = t.customer_id
WHERE t.spent > 500;

The average that isn’t allowed there

Spot the bugOrders bigger than usual

Tap the line with the bug.

SELECT id, customer_id, total
FROM orders
WHERE status = 'PAID'
  AND total > avg(total)
ORDER BY total DESC;

Deep diveA correlated subquery per row, and how to turn it into a joinInterview favorite

An admin list shows customers with their order count and last order date:

SELECT c.id, c.name,
       (SELECT count(*)        FROM orders o WHERE o.customer_id = c.id) AS orders,
       (SELECT max(created_at) FROM orders o WHERE o.customer_id = c.id) AS last_order
FROM customers c
ORDER BY c.name;

EXPLAIN shows two SubPlans executed for every customer: 200,000 customers mean 400,000 index probes. For a page of 50 with LIMIT that’s fine. For the CSV export of all customers it takes minutes.

Aggregate once and join:

SELECT c.id, c.name, COALESCE(s.orders, 0) AS orders, s.last_order
FROM customers c
LEFT JOIN (
    SELECT customer_id, count(*) AS orders, max(created_at) AS last_order
    FROM orders GROUP BY customer_id
) s ON s.customer_id = c.id
ORDER BY c.name;

One scan of orders, one hash join. Points worth making: LEFT JOIN plus COALESCE keeps customers without orders at 0 (the scalar subquery gave 0 for count and NULL for max automatically); the per-row form can still win with a small LIMIT on an indexed outer query, because it avoids aggregating all orders; and LATERAL gives you the per-row shape explicitly when you want it.

  • Scalar subquery: ≤ 1 row (0 → NULL, 2 → error). Derived tables need an alias (optional in PostgreSQL 16+).
  • Uncorrelated = once (InitPlan); correlated = per outer row (SubPlan). EXISTS/IN become semi/anti-joins; scalar subqueries in SELECT usually don’t.
  • Rewrite per-row aggregates as a grouped derived table + LEFT JOIN, or LATERAL for top-N.
  • NOT IN + NULL returns nothing; = ANY($1) binds a list.

Check this part

  1. How do you find products priced above the average price?

  2. What makes a subquery correlated?

  3. A scalar subquery in SELECT matches no rows for some outer row. What do you get?

  4. Two scalar subqueries per customer make an export slow. Usual fix?

A subquery is a SELECT inside another statement: a single value in WHERE or SELECT, a list for IN, a table in FROM (with an alias), or a test with EXISTS. A correlated subquery refers to the outer row and runs once per row; a scalar subquery must return at most one row.

Part Not started

WITH: naming the steps of a query

“Customers who spend more than the average customer” takes three steps: total per customer, the average of those totals, then the comparison. With subqueries, you’d nest them inside each other and read the query from the inside out.

A CTECommon table expressionA named query step written with WITH, used by the rest of the statement like a table.Open in glossary → (common table expression) lets you write the steps in order, each with a name, like variables:

WITH spending AS (                      -- step 1: total per customer
    SELECT customer_id, sum(total) AS spent
    FROM orders
    WHERE status = 'PAID'
    GROUP BY customer_id
),
average AS (                            -- step 2: the average of those totals
    SELECT avg(spent) AS avg_spent FROM spending
)
SELECT s.customer_id, s.spent           -- step 3: compare
FROM spending s, average a
WHERE s.spent > a.avg_spent
ORDER BY s.spent DESC;
  • WITH name AS (…) defines a step. Separate several with commas; each can use the ones before it.
  • The steps exist only while this one statement runs. They aren’t saved anywhere.
  • The statement ends with a normal query that uses them. A step nobody uses is simply ignored.

FROM spending s, average a pairs every customer with the single average row. Since average has exactly one row, that’s safe here.

  • Optimization: before PostgreSQL 12, every CTE was materialized and acted as an optimization fence (filters weren’t pushed into it). Since 12, a non-recursive, side-effect-free CTE referenced once is inlined like a subquery; one referenced twice is computed once and stored. Override with AS MATERIALIZED (compute once, e.g. an expensive call used twice, or to stop a bad pushdown) or AS NOT MATERIALIZED. MySQL 8.0+, SQL Server and SQLite 3.8.3+ support CTEs, each with its own materialization rules.
  • Scope: a CTE belongs to one statement. For reuse across statements: a view, a temporary table (with ANALYZE so the planner has statistics), or a materialized view.
  • Data-modifying CTEs (PostgreSQL): INSERT/UPDATE/DELETE … RETURNING inside WITH, used by the main statement. All parts see the same snapshot and run exactly once, even if not referenced; they can’t see each other’s changes to the same table except through RETURNING.
  • Testing: each CTE can be run on its own by changing the final SELECT, which is the practical reason to prefer them in analytics code.

Predict the output

orders has 1,000 rows, 600 of them PAID. What does this return?

WITH paid AS (
    SELECT * FROM orders WHERE status = 'PAID'
)
SELECT count(*) FROM orders;
WITH monthly AS (
    SELECT date_trunc('month', created_at) AS month, sum(total) AS revenue
    FROM orders
    WHERE status = 'PAID' AND created_at >= date '2026-01-01'
    GROUP BY 1
),
stats AS (
    SELECT avg(revenue) AS avg_revenue FROM monthly
)
SELECT m.month,
       m.revenue,
       round(100.0 * m.revenue / s.avg_revenue - 100, 1) AS vs_average_pct
FROM monthly m
CROSS JOIN stats s
ORDER BY m.month;

Practice: first-time and returning customers

Exercisemedium

Who came back?

For each customer who has at least one paid order, show their id, the date of their first paid order, and how many paid orders they placed after that first one. Use a CTE for the first-order dates.

›

Step 1: min(created_at) per customer, from paid orders. That’s a GROUP BY inside a CTE.

›

Step 2: join the CTE back to orders and count orders with created_at later than the first date. A customer with only one order should show 0, so think about which join keeps them.

SolutionTry it yourself first
WITH first_orders AS (
    SELECT customer_id, min(created_at) AS first_at
    FROM orders
    WHERE status = 'PAID'
    GROUP BY customer_id
)
SELECT f.customer_id,
       f.first_at::date   AS first_order,
       count(o.id)        AS repeat_orders
FROM first_orders f
LEFT JOIN orders o
       ON o.customer_id = f.customer_id
      AND o.status = 'PAID'
      AND o.created_at > f.first_at
GROUP BY f.customer_id, f.first_at
ORDER BY repeat_orders DESC;

LEFT JOIN keeps customers with no later orders, and count(o.id) counts them as 0 (count(*) would count the empty row as 1). The conditions on the joined orders sit in ON, so they don’t turn the left join into an inner one.

Deep diveMoving rows in one statement with a data-modifying CTEInterview favorite

Archiving old orders as two statements (INSERT INTO archive SELECT …, then DELETE …) has two gaps: between them, new rows can start matching the condition and get deleted without being archived, and a crash between the two leaves duplicates unless both run in one transaction.

In PostgreSQL, one statement does both, and the delete decides exactly which rows move:

WITH moved AS (
    DELETE FROM orders
    WHERE status IN ('DELIVERED', 'CANCELLED')
      AND created_at < now() - interval '2 years'
    RETURNING *
)
INSERT INTO orders_archive
SELECT * FROM moved;

Every row the DELETE removed is the row that gets inserted, atomically. Follow-ups:

  • Batching: millions of rows in one statement hold locks and bloat WAL. Limit each run, for example WHERE id IN (SELECT id FROM orders WHERE … ORDER BY id LIMIT 5000 FOR UPDATE SKIP LOCKED), and loop until it moves 0 rows. SKIP LOCKED lets several workers run without blocking each other.
  • Snapshot: the sub-statements see the database as it was when the statement started, so the INSERT can’t read orders to find the rows the DELETE just removed: it must use moved.
  • Children: order_items with ON DELETE CASCADE disappear too; archive them first in another CTE, or the archive loses the lines.
  • Alternatives: partitioning orders by month and detaching old partitions is far cheaper for time-based retention.
  • WITH a AS (…), b AS (…) SELECT …: steps in reading order, scoped to one statement.
  • PostgreSQL 12+: single-reference CTEs inlined; multi-reference materialized; AS [NOT] MATERIALIZED to control.
  • Data-modifying CTEs: DELETE … RETURNING feeding INSERT, same snapshot, all run once; batch with LIMIT … FOR UPDATE SKIP LOCKED.
  • Cross-statement reuse: views, temp tables (+ ANALYZE), materialized views.
WITH totals AS MATERIALIZED (
    SELECT customer_id, sum(total) AS spent FROM orders GROUP BY customer_id
)
SELECT * FROM totals WHERE spent > (SELECT avg(spent) FROM totals);

Check this part

  1. What does WITH spending AS (…) do?

  2. A CTE is defined but the final SELECT reads from the original table. What happens to the CTE?

  3. In PostgreSQL 12+, when is a non-recursive CTE materialized by default?

  4. Why archive with WITH moved AS (DELETE … RETURNING *) INSERT … SELECT * FROM moved?

WITH name AS (query) names a step, and later steps and the main query use it like a table. CTEs make long queries readable top to bottom. PostgreSQL 12+ inlines them unless they're used twice or marked MATERIALIZED. Data-modifying CTEs move rows in one statement.

Part Not started

Recursive CTEs: trees and chains

Categories form a tree: Electronics contains Phones and Laptops, Phones contains Android and iPhone, and so on. Each category stores its parent, and each product stores its category_id:

idnameparent_id
1ElectronicsNULL
2Phones1
3Laptops1
4Android2
5iPhone2

“All categories under Electronics” needs one join per level, and you don’t know how many levels there are. A recursive CTE repeats a step until there’s nothing left to find:

WITH RECURSIVE tree AS (
    SELECT id, name, 0 AS depth                  -- 1. start: Electronics
    FROM categories
    WHERE id = 1

    UNION ALL

    SELECT c.id, c.name, t.depth + 1             -- 2. repeat: children of the rows found last time
    FROM categories c
    JOIN tree t ON c.parent_id = t.id
)
SELECT * FROM tree ORDER BY depth, name;

How it runs:

  1. The first part (the anchor) runs once: Electronics, depth 0.
  2. The second part runs with tree = the rows found in the previous round: children of Electronics, Phones and Laptops (depth 1).
  3. Again, with those two: Android and iPhone (depth 2).
  4. Again: nobody has Android or iPhone as a parent, so no new rows. It stops.

UNION ALL glues the rounds together. The recursion stops when a round finds no rows, so there must always be a point where nothing new matches.

  • Semantics: the non-recursive term runs once; the recursive term runs repeatedly against the previous iteration’s rows (the working table), not the whole result, until it returns nothing. UNION instead of UNION ALL discards rows already produced, which can stop simple cycles but costs a hash of everything.
  • Termination: trees from foreign keys end naturally; graphs with cycles (referrals, “follows”, bill of materials with bad data) don’t. Track a path (ARRAY[id], NOT id = ANY(path)) or use PostgreSQL 14+‘s CYCLE id SET is_cycle USING path. Add a depth < 20 guard as a safety net anyway.
  • Order: rows come out breadth-first in practice, but without ORDER BY that isn’t guaranteed. PostgreSQL 14+ has SEARCH DEPTH FIRST BY id SET ord / BREADTH FIRST for a sortable column; earlier, sort by a path array.
  • Uses: descendants and ancestors (walk t.parent_id = c.id to go up), org charts, threaded comments, shortest hop count in small graphs, number/date series where generate_series doesn’t exist (MySQL 8, SQLite).
  • Performance: an index on parent_id; each iteration is a join. For large, read-heavy trees prefer a different model: materialized path, ltree, nested sets, or a closure table, all of which answer “all descendants” without recursion.

Predict the output

What does this return?

WITH RECURSIVE n(x) AS (
    SELECT 1
    UNION ALL
    SELECT x + 1 FROM n WHERE x < 5
)
SELECT x FROM n;
-- products in Phones or any of its subcategories
WITH RECURSIVE sub AS (
    SELECT id FROM categories WHERE id = 2
    UNION ALL
    SELECT c.id FROM categories c JOIN sub s ON c.parent_id = s.id
)
SELECT p.id, p.name FROM products p WHERE p.category_id IN (SELECT id FROM sub);

-- breadcrumbs: from iPhone up to the root
WITH RECURSIVE up AS (
    SELECT id, name, parent_id, 0 AS level FROM categories WHERE id = 5
    UNION ALL
    SELECT c.id, c.name, c.parent_id, u.level + 1
    FROM categories c JOIN up u ON c.id = u.parent_id
)
SELECT string_agg(name, ' › ' ORDER BY level DESC) AS breadcrumbs FROM up;
-- Electronics › Phones › iPhone

The recursion that doesn’t stop

Spot the bugCalendar of the next 30 days

Tap the line with the bug.

WITH RECURSIVE days AS (
    SELECT current_date AS day
    UNION ALL
    SELECT day + 1 FROM days
)
SELECT day FROM days;

Deep diveThe referral chain that never endsInterview favorite

referrals(user_id, referred_by) records who invited whom. “Everyone in Ana’s downline” is a recursive walk. Then a support agent fixes a mistake by hand, and user 7 is now referred by user 12, who was referred by user 7. The query runs until temp_file_limit or statement timeout kills it, and the rewards job that runs it every night fails.

Detect cycles by carrying the path:

WITH RECURSIVE downline AS (
    SELECT user_id, ARRAY[user_id] AS path, 1 AS depth
    FROM referrals WHERE referred_by = 42

    UNION ALL

    SELECT r.user_id, d.path || r.user_id, d.depth + 1
    FROM referrals r
    JOIN downline d ON r.referred_by = d.user_id
    WHERE NOT r.user_id = ANY (d.path)          -- don't revisit
      AND d.depth < 50                          -- safety net
)
SELECT user_id, depth FROM downline;

PostgreSQL 14+ can do the bookkeeping: … ) CYCLE user_id SET is_cycle USING path marks the row that closes a loop and stops there, so you can also report the cycles instead of silently skipping them.

The interview answer has three layers: stop the query (path check, depth limit, statement_timeout), find out whether the data model should forbid cycles (a trigger that checks ancestry before insert, or a closure table that makes the check one lookup), and note that UNION instead of UNION ALL only prevents revisiting identical rows, so it fails as soon as rows carry a growing depth or path.

  • Anchor once, recursive term against the previous iteration’s rows, stops on an empty iteration. UNION ALL normally; UNION dedups whole rows only.
  • Cycles: path array + NOT id = ANY(path), or PostgreSQL 14+ CYCLE … SET … USING; plus a depth guard and statement_timeout.
  • Order with SEARCH DEPTH/BREADTH FIRST (14+) or a path array; index parent_id.
  • Heavy tree reads: materialized path, ltree, closure table.

Check this part

  1. When does a recursive CTE stop?

  2. In a category tree, how do you walk down to the children of the rows found so far?

  3. Why does switching UNION ALL to UNION not protect a downline query with a depth column from cycles?

  4. A read-heavy app asks for "all descendants" constantly on a big tree. What helps most?

WITH RECURSIVE starts from an anchor query and repeatedly joins the previous step's rows until no new rows come out: category trees, org charts, number and date series. Always make sure it stops: a WHERE limit, a depth column, or cycle detection with a path array or CYCLE.

Key takeaways

  • A subquery in parentheses gives a value, a list, a table (with a name) or a yes/no (EXISTS). Aggregates go in a subquery, not in WHERE.
  • A scalar subquery must return at most one row.
  • A correlated subquery runs once per outer row; a join with GROUP BY often does the same in one pass.
  • WITH names the steps of a query in reading order. Make sure the final query uses them.
  • WITH RECURSIVE walks trees: an anchor, a repeating part, and a condition that eventually finds nothing.
  • InitPlan vs SubPlan; scalar subqueries in SELECT usually aren’t decorrelated, so rewrite them as grouped joins for big result sets.
  • PostgreSQL 12+ CTE inlining and MATERIALIZED; data-modifying CTEs for atomic moves, batched with SKIP LOCKED.
  • Recursive CTEs iterate over the previous step’s rows; guard against cycles with paths, CYCLE, depth limits and timeouts.
  • For hot hierarchical reads, choose a tree model instead of recursion.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.