What is a CTE (WITH) and why is it needed?
A CTE (WITH) names an intermediate result for the duration of one query, so the query reads top to bottom. A CTE can be referenced several times. WITH RECURSIVE, a starting query plus a recursive one joined by UNION ALL, walks hierarchies. A CTE is mainly about readability, not speed; in PostgreSQL 12+ MATERIALIZED and NOT MATERIALIZED control whether it is inlined into the query.
SQL · Subqueries, CTE, sets
A 40-line query with three levels of subqueries. How to split it into steps that read well?
A report "users whose completed payments exceed 500" starts with one subquery and within a month grows two more. It has to be read from the inside out, and even the author gets lost a week later. A CTE (Common Table Expression, WITH) gives each step a name and lays the query out top to bottom. It is the simplest way to make SQL understandable for a colleague who will review it.
How it works and why. A CTE names an intermediate result for the duration of one query. After WITH name AS (…) the name is used in the main query like an ordinary table. Several CTEs can be declared separated by commas, and each next one sees the previous ones. The name lives only within this query. For a reader they are "variables" for results, and for the database a tool too: one CTE can be referenced several times without repeating a complex subquery.
Take the sample data: transactions 100 and 300 belong to account 10 (user 1), 50 is failed (account 11), 200 and 400 belong to account 12 (user 2), 80 to account 13 with no owner. First the query with a nested subquery:
-- nested subqueries: read from the inside out
SELECT u.email, s.total
FROM users u
JOIN (
SELECT a.user_id, SUM(t.amount) AS total
FROM transactions t
JOIN accounts a ON a.id = t.account_id
WHERE t.status = 'completed'
GROUP BY a.user_id
) s ON s.user_id = u.id
WHERE s.total > 500;
The completed sums: user 1 has 100 + 300 = 400, user 2 has 200 + 400 = 600, the account without an owner makes a group with NULL and the sum 80, which the JOIN with users drops. Only bohdan meets "more than 500". The same query, but with a CTE:
-- the same query as a CTE: reads top to bottom; result bohdan, 600
WITH totals AS (
SELECT a.user_id, SUM(t.amount) AS total
FROM transactions t
JOIN accounts a ON a.id = t.account_id
WHERE t.status = 'completed'
GROUP BY a.user_id
)
SELECT u.email, s.total
FROM totals s
JOIN users u ON u.id = s.user_id
WHERE s.total > 500;
The difference is not speed but that the step "compute the totals" is now named and lies apart from the step "join the users". Adding a check to it or moving it to a separate query for debugging is easy: just run the content of the CTE alone.
A recursive CTE walks a tree
| id | parent_id | name |
|---|---|---|
| 1 | NULL | Electronics |
| 2 | 1 | Phones |
| 3 | 1 | Laptops |
| 4 | 2 | Android |
| name | depth |
|---|---|
| Electronics | 0 |
| Phones | 1 |
| Laptops | 1 |
| Android | 2 |
The recursive form WITH RECURSIVE has two parts joined by UNION ALL: a starting query (the root) and a recursive one that refers to the CTE itself. The database repeats the second part while it produces new rows. This is how hierarchies are walked: a category tree, a reporting line, nested comments.
-- all subcategories of category 1 with depth
WITH RECURSIVE tree AS (
SELECT id, name, 0 AS depth
FROM categories
WHERE id = 1
UNION ALL
SELECT c.id, c.name, tree.depth + 1
FROM categories c
JOIN tree ON c.parent_id = tree.id
)
SELECT name, depth FROM tree ORDER BY depth, id;
In PostgreSQL a CTE can even be combined with data changes: DELETE … RETURNING inside WITH deletes and returns what was deleted at once. This is handy for cleaning up test data with a count:
-- PostgreSQL: delete and see at once what was deleted
WITH gone AS (
DELETE FROM transactions
WHERE status = 'failed'
RETURNING id, account_id
)
SELECT count(*) AS deleted FROM gone;
Limits and alternatives. In PostgreSQL before version 12 a CTE was always materialised, so it acted as a wall for the optimiser. Since version 12 an ordinary CTE without side effects and with a single reference is inlined into the main query, and if there are several references it is computed once. This can be changed with the keywords MATERIALIZED and NOT MATERIALIZED:
WITH totals AS MATERIALIZED (
SELECT account_id, SUM(amount) AS total
FROM transactions
GROUP BY account_id
)
SELECT * FROM totals;
In other databases the behaviour depends on the version and the engine (MySQL supports CTEs from 8.0). So a CTE should be considered neither "faster" nor "slower" than a subquery: compare plans with EXPLAIN. A temporary table is better when the intermediate result is large and is read several times by different queries, because it can be indexed. For simple one-step queries a CTE is unnecessary.
Typical mistakes.
- Expecting a CTE to always run once and "cache" the result: in PostgreSQL 12+ it depends on the number of references and the keywords.
- Forgetting the stop condition in the recursive part: on data with a cycle (a category refers to its ancestor) the query never ends. A depth field with a limit or a check of visited ids helps.
- Using
UNIONinstead ofUNION ALLin recursion without need: needless duplicate removal on every step. - Assuming the CTE name is visible in the next separate query: it lives only within one.
Check yourself
How does a CTE differ from a subquery in FROM and from a temporary table?
Answer
A CTE is a named subquery for the duration of one query: it can be referenced several times and reads top to bottom. A temporary table physically exists for the session, can be indexed and used in many queries. A subquery in FROM has no name and is used once.
Why does a recursive CTE need UNION ALL and what does each of the two parts do?
Answer
The first part gives the starting rows (the root of the tree), the second takes rows from the previous step and adds their children. The database repeats the second part while it returns new rows. UNION ALL joins the results of the steps without removing duplicates.