Subqueries, CTEs & recursive CTEs
Break complex queries into readable CTEs and walk hierarchies recursively.
By Invicly Tech, , in SQL & PostgreSQL. About 10 minutes to read.
In short
A subquery is a query inside another query. CTEs (WITH clauses) name those steps so complex logic reads top to bottom, and recursive CTEs repeat a step to walk hierarchies like org charts or category trees.
Explained simply
Some questions need two steps. "Which products cost more than the average product?" First you work out the average, then you compare each product to it. A subquery lets you put the first step inside the second, in brackets, as one query.
A CTE (common table expression) does the same job but gives each step a name at the top, using WITH. It reads like a recipe: first make the paid orders, then total them per customer, then pick the best customers.
Neither one stores anything permanently. They are temporary helper results that exist only while the query runs. Think of them as scratch paper you throw away when the answer is written down.
Recursive CTEs are a special kind that can refer to themselves. They repeat a step until nothing new turns up, which is exactly what you need to walk a family tree, an org chart, or folders inside folders.
Press Play on a diagram to walk through it one step at a time.
- Step 1WITH paid AS (...)
Step 1: filter paid orders
- Step 2totals AS (...)
Step 2: sum per customer from paid
- Step 3ranked AS (...)
Step 3: rank customers by total
- Step 4Final SELECT
Read from the last step
- 1Anchor query
Start rows, e.g. the CEO
- 2Recursive step
Join previous rows to their children
- 3Append new rows
Add them to the result
- 4Repeat until empty
Stops when a step finds no new rows
- Back to step 1
- WHERE id IN (SELECT customer_id ...)
- Easy to read
- Avoid NOT IN if NULLs are possible
- WHERE EXISTS (SELECT 1 ... WHERE o.customer_id = c.id)
- Stops at the first match
- NOT EXISTS is NULL-safe
- JOIN orders, then DISTINCT
- Repeats rows before DISTINCT
- Use only when you need order columns
In depth
Where a subquery can live
What a subquery returns decides where it can go. A scalar subquery returns exactly one value, one row and one column, so it can sit anywhere a single value can: SELECT name, (SELECT AVG(price) FROM products) AS avg_price. If it returns more than one row, Postgres raises an error.
A subquery that returns one column of many rows can feed IN, ANY or ALL: WHERE id IN (SELECT customer_id FROM orders). A subquery that returns a full table can go in FROM, where it must have an alias: FROM (SELECT ...) AS t.
EXISTS (SELECT 1 FROM ...) only cares whether at least one row comes back. The selected columns do not matter, which is why people write SELECT 1.
- One value: SELECT list, WHERE x = (...)
- One column: IN, ANY, ALL
- Full table: FROM (...) AS alias
- Yes or no: EXISTS / NOT EXISTS
Correlated subqueries and how Postgres runs them
A correlated subquery uses a column from the outer row, such as WHERE o.customer_id = c.id. Logically it runs once per outer row, which sounds slow.
In practice, the planner rewrites many of them. EXISTS and NOT EXISTS are usually turned into a semi-join or anti-join, which can use hash or merge joins and is very fast. Scalar correlated subqueries in the SELECT list are not rewritten and really do run per row, so on large results it is often faster to join to a pre-grouped subquery instead.
CTEs and performance
Since PostgreSQL 12, a CTE that is used once and has no side effects is folded into the main query, just like a subquery. The planner can push filters into it and use indexes. So using CTEs for readability costs nothing in the common case.
If a CTE is referenced more than once, Postgres computes it once and stores the result, called materialising. You can force either behaviour: WITH t AS MATERIALIZED (...) computes it once and acts as a fence, and AS NOT MATERIALIZED lets it be inlined. Reach for these only after EXPLAIN shows a problem.
- Used once, no side effects (PG 12+)
- Or forced with NOT MATERIALIZED
- Filters pushed in, indexes usable
- Same plan as a subquery
- Referenced more than once
- Or forced with MATERIALIZED
- Computed once and stored
- Acts as an optimisation fence
Making recursive CTEs safe
A recursive CTE stops when a round produces no new rows. If the data has a loop, for example A reports to B and B reports to A, it never stops.
Two simple guards help. Keep a depth counter and add WHERE depth < 20 in the recursive part. Or keep a path array of visited ids and skip any row already in it: WHERE NOT e.id = ANY(path). PostgreSQL 14 and later also offer a built-in CYCLE clause that does this for you.
Use UNION ALL in recursive CTEs unless you really need duplicates removed. UNION also prevents some loops, but it compares whole rows, so it does not help when a depth column changes each round.
- Depth counter
- WHERE depth < 20
- Path of visited ids
- WHERE NOT e.id = ANY(path)
- CYCLE clause
- Built in, PostgreSQL 14+
Learn it in 4 short steps
About 1h each. Track them with a timer in your plan.
- 1Write scalar and correlated subqueries~1h
- 2Use EXISTS and IN subqueries~1h
- 3Refactor queries into CTEs~1h
- 4Walk a hierarchy with a recursive CTE~1h
Key points
- A scalar subquery returns one value; it can appear in SELECT or WHERE.
- A correlated subquery refers to the outer row and runs per row logically.
- EXISTS stops at the first match and handles NULLs safely.
- WITH RECURSIVE needs an anchor, UNION ALL, and a step that eventually finds nothing.
Key terms
Tap a card to flip it. 0/5 known
Examples
WITH RECURSIVE chain AS (
SELECT id, name, manager_id, 1 AS depth
FROM employees
WHERE manager_id IS NULL -- anchor: the CEO
UNION ALL
SELECT e.id, e.name, e.manager_id, c.depth + 1
FROM employees e
JOIN chain c ON e.manager_id = c.id -- recursive step
)
SELECT repeat(' ', depth - 1) || name AS org_chart
FROM chain
ORDER BY depth, name;Products priced above their category average
Step 1: the inner query needs the average for the product's own category, so it must refer to the outer row; that makes it correlated. Step 2: compare each product's price to that value. Step 3: for big tables, the CTE version computes all averages once and joins them, which avoids running the subquery per row.
-- correlated subquery
SELECT name, category, price
FROM products p
WHERE price > (SELECT AVG(price) FROM products WHERE category = p.category);
-- same result with a CTE + join
WITH avg_cat AS (
SELECT category, AVG(price) AS avg_price FROM products GROUP BY category
)
SELECT p.name, p.category, p.price
FROM products p JOIN avg_cat a USING (category)
WHERE p.price > a.avg_price;Breadcrumbs for a category tree
categories(id, name, parent_id) stores a tree. For category 42 we want "Home > Kitchen > Knives". Step 1: the anchor selects category 42. Step 2: the recursive part joins each row to its parent. Step 3: it stops at the root, whose parent_id is NULL, because the join finds nothing. Step 4: string_agg joins the names, ordering by depth from the top down.
WITH RECURSIVE up AS (
SELECT id, name, parent_id, 0 AS depth
FROM categories WHERE id = 42
UNION ALL
SELECT c.id, c.name, c.parent_id, up.depth + 1
FROM categories c JOIN up ON c.id = up.parent_id
)
SELECT string_agg(name, ' > ' ORDER BY depth DESC) AS breadcrumb
FROM up;Quick reference
- Scalar subquery must return 1 row and 1 column, or it errors
- Subquery in FROM needs an alias: FROM (SELECT ...) AS t
- EXISTS (SELECT 1 ...): only whether a row exists matters
- WITH a AS (...), b AS (SELECT ... FROM a) SELECT ... FROM b;
- Since PG 12, single-use CTEs are inlined; AS MATERIALIZED forces a fence
- WITH RECURSIVE: anchor UNION ALL step; stop with a depth limit or CYCLE clause
- NOT EXISTS beats NOT IN when the subquery can contain NULL
Common mistakes
- Recursive CTEs that never stop because data contains a cycle.
- NOT IN with a subquery that can return NULL, which returns no rows.
- Deeply nested subqueries where a few named CTEs would be clearer.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
List employees(name, salary) who earn more than the company-wide average salary.
- Exercise 2medium
Using CTEs, find the share of total paid revenue that comes from the top 10 customers.
- Exercise 3hard
From employees(id, name, manager_id), list everyone who reports (directly or indirectly) to employee 7, with their depth, protected against cycles.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Is a CTE faster than a subquery?
- Usually they perform the same in modern Postgres, because single-use CTEs are inlined. Choose CTEs for readability and check EXPLAIN if speed matters.
- Can a CTE modify data?
- Yes. WITH can contain INSERT, UPDATE or DELETE with RETURNING, and the main query can use those returned rows, for example to move rows between tables in one statement.
- Is a recursive CTE really recursive?
- Not quite. It is a loop: each round takes only the rows added by the previous round, joins them again, and stops when nothing new appears.