Sub topic 13
Performance and indexing for recursive queries
This chapter assumes you can write a recursive CTE with an anchor member and a recursive member, and that you know how the working table drives each iteration. It also assumes you can read a basic query plan with EXPLAIN. Here you will learn why recursive queries get slow, which indexes help, and how to keep the row count under control.
Where the cost comes from
A recursive CTE runs its recursive member once per iteration. Each iteration reads the rows produced by the previous one (the working table) and joins them to a base table. The total cost is roughly:
- the number of iterations, multiplied by
- the cost of one join from the working table to the base table.
Two things dominate that cost. The first is how the join finds matching rows in the base table. The second is how many rows the recursion produces in total. A slow recursive query is almost always slow for one of those two reasons.
Index the join column
In the org chart query, the recursive member is:
SELECT e.id, e.name, e.manager_id, c.depth + 1
FROM employees e
JOIN chain c ON e.manager_id = c.idFor every row in the working table, the database must find all employees whose manager_id equals that row's id. Without an index on employees.manager_id, each iteration scans the whole employees table. With an index, each working-table row costs one index lookup.
CREATE INDEX idx_employees_manager_id ON employees (manager_id);The same rule applies to other shapes:
| Query shape | Join condition in the recursive member | Index to create |
|---|---|---|
| Org chart (parent to children) | `e.manager_id = c.id` | `employees (manager_id)` |
| Graph reachability | `e.src = r.dst` | `edges (src)` |
| Bill of materials | `b.assembly_id = x.component_id` | `bom (assembly_id)` |
| Walking upward (child to parent) | `e.id = c.manager_id` | primary key on `employees (id)`, usually already present |
The index must be on the column in the base table that is compared against the working table. Indexing the working table is not possible, because it is a temporary structure the database manages itself.
A composite index can also make the lookup index-only. For the bill of materials, bom (assembly_id, component_id, qty) lets the recursive member read everything it needs from the index without visiting the table. Some engines support INCLUDE columns for this, for example PostgreSQL 11 and later and SQL Server:
CREATE INDEX idx_bom_assembly
ON bom (assembly_id) INCLUDE (component_id, qty);Check your own engine's syntax. MySQL and SQLite do not have INCLUDE, so use a composite index there.
Check the plan
Run EXPLAIN (or EXPLAIN ANALYZE in PostgreSQL) on the query. In PostgreSQL, a recursive CTE appears as a Recursive Union node. The anchor is the first child, and the recursive member is the second child, which contains a WorkTable Scan.
EXPLAIN ANALYZE
WITH RECURSIVE chain AS (
SELECT id, name, manager_id, 0 AS depth
FROM employees
WHERE manager_id IS NULL
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
)
SELECT id, name, depth FROM chain;Look for these signs:
- A
Seq Scan on employeesinside the recursive member means the join column has no usable index. The scan repeats once per iteration, so its cost multiplies. - A
loops=value on the recursive child shows how many iterations ran. A large number means a deep hierarchy or a runaway recursion. - A
rows=value that is far larger than your table size means the recursion produces duplicates. This points to the problems in the next section.
Plan details differ across engines. SQL Server shows an Index Spool or Table Spool for the recursive part. MySQL's EXPLAIN lists the recursive member as a DERIVED or UNION step. In all of them, you are looking for full scans repeated per iteration.
Control the number of rows produced
Indexes make each iteration cheaper. They do not reduce how many rows the recursion generates. Several patterns multiply rows without adding information.
Duplicate paths in graphs
In a graph, the same node can be reached by many different routes. With UNION ALL, each route produces its own row, and the later iterations expand each of those copies again. A graph with a few dozen nodes can generate millions of rows this way, even when it has no cycles.
Consider a layered graph where every node in layer 1 connects to every node in layer 2, and so on. If each layer has 5 nodes, the number of distinct paths from the first layer to the nth grows as 5 to the power n. The number of reachable nodes stays at 5 per layer.
If you only need to know which nodes are reachable, and not the paths, you can switch to UNION. The database then discards rows that duplicate an existing row, so each node is expanded once:
WITH RECURSIVE reach(node) AS (
SELECT 1
UNION
SELECT e.dst
FROM reach r
JOIN edges e ON e.src = r.node
)
SELECT node FROM reach;This works only if the rows really are identical. If you carry a path or depth column, every route produces a different row, and UNION removes nothing. Keep the recursive output to the columns you need. Dropping path and depth can turn an exponential query into a linear one.
UNION has a cost of its own. The database must keep a structure of all rows seen so far, usually a hash table or a sorted set, and check each new row against it. This uses memory proportional to the result size. PostgreSQL, MySQL, and SQLite support this form. SQL Server does not allow UNION in a recursive CTE, so you must prevent duplicates yourself, for example with a visited-node check or by deduplicating the edges first.
Filter early
Put restrictions in the recursive member's WHERE clause, not in the outer query. A filter in the outer query runs after the recursion has produced every row.
Slow:
WITH RECURSIVE chain AS (
SELECT id, name, manager_id, 0 AS depth
FROM employees
WHERE manager_id IS NULL
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
)
SELECT * FROM chain WHERE depth <= 3;Better:
WITH RECURSIVE chain AS (
SELECT id, name, manager_id, 0 AS depth
FROM employees
WHERE manager_id IS NULL
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
WHERE c.depth < 3
)
SELECT * FROM chain;The second version stops after level 3. The first walks the entire tree and then discards most of the rows. Some optimizers can push simple filters inward, but a recursive CTE is usually an optimization barrier, so do not rely on it.
The same advice applies to the anchor. If you need the subtree under one manager, start the anchor at that manager (WHERE id = 42) rather than computing every subtree and filtering later.
Carry fewer and narrower columns
Every column in the CTE is stored in the working table and copied each iteration. Wide text columns and long arrays add up. Carry only the key and the values you need, and join back to the base table in the outer query for the rest:
WITH RECURSIVE chain AS (
SELECT id, 0 AS depth
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT e.id, c.depth + 1
FROM employees e
JOIN chain c ON e.manager_id = c.id
)
SELECT e.id, e.name, e.email, c.depth
FROM chain c
JOIN employees e ON e.id = c.id
ORDER BY c.depth, e.name;Path arrays deserve particular care. A path of length d is copied for every row at depth d, so memory grows with both depth and row count. In cycle-guarded graph queries, expect this to be the largest cost.
Memory, temporary storage, and limits
The database holds the working table and the accumulated result. When they exceed the memory budget, the engine spills to disk:
- PostgreSQL uses
work_memfor the tuplestores behind the recursion. Large results spill to temporary files. - MySQL materializes the CTE in an internal temporary table. When it passes
tmp_table_sizeormax_heap_table_size, it converts to an on-disk table. The settingcte_max_recursion_depth(default 1000) bounds the iteration count. - SQL Server stops at 100 levels unless you add
OPTION (MAXRECURSION n). The value0removes the limit, which is risky on data you do not trust. - SQLite has no default iteration cap, so a missing termination condition runs until you interrupt it or add a
LIMIT.
A LIMIT in the outer query can act as a safety net in PostgreSQL, MySQL, and SQLite, because the recursion can stop once enough rows exist. Treat it as a guard against accidents, not as the termination condition.
Statistics and the planner
The planner has little information about how many iterations a recursive CTE will run. PostgreSQL, for example, uses a fixed rough estimate for the recursive term's output. This can lead to a poor plan for the outer query, such as a nested loop over a result with millions of rows when a hash join would be better.
Practical steps:
- Keep table statistics current with
ANALYZE(PostgreSQL),ANALYZE TABLE(MySQL), orUPDATE STATISTICS(SQL Server). Good statistics improve the recursive member's join, even if the CTE's own row count remains a guess. - If the outer query joins the CTE to a large table and the plan is poor, materialize the CTE result into a temporary table, index it, and run the second step against that. This costs a write but gives the planner real row counts.
CREATE TEMPORARY TABLE subtree AS
WITH RECURSIVE chain AS (
SELECT id, 0 AS depth
FROM employees
WHERE id = 42
UNION ALL
SELECT e.id, c.depth + 1
FROM employees e
JOIN chain c ON e.manager_id = c.id
)
SELECT id, depth FROM chain;
CREATE INDEX idx_subtree_id ON subtree (id);
ANALYZE subtree;Measure before you change anything
A useful routine for a slow recursive query:
- Run
EXPLAIN ANALYZEand look for repeated sequential scans in the recursive member. - Index the base table's join column and run it again.
- Count the rows the CTE produces and compare to the number of distinct nodes. A large gap means duplicate paths.
- Remove unneeded columns, add a depth bound, and move filters into the recursive member.
- If the outer query is still slow, materialize the CTE result.
If a query is run constantly on a large, deep, or frequently queried hierarchy, and these steps are not enough, the structure itself may be the problem. The final chapter covers alternatives such as closure tables and materialized paths, which move the cost from read time to write time.
Exercise
A recursive CTE walks a bill of materials with the recursive member JOIN bom b ON b.assembly_id = x.component_id. The bom table has 5 million rows and has only a primary key on (id). The query takes minutes. Name the first index you would add and explain how you would confirm it helped.
Show answer
Add an index on bom (assembly_id), ideally covering component_id and qty too, for example CREATE INDEX idx_bom_assembly ON bom (assembly_id, component_id, qty);. Without it, each iteration scans all 5 million rows to find the children of the current working-table rows. To confirm, run EXPLAIN ANALYZE before and after. The Seq Scan on bom inside the recursive member should become an index scan, and total execution time should fall sharply.
Exercise
A reachability query over a graph uses UNION ALL and carries a path array. It returns millions of rows for a graph with 200 nodes, and you only need the set of reachable nodes. What would you change, and why does it help?
Show answer
Drop the path column and switch to UNION (in an engine that allows it, such as PostgreSQL), selecting only the node. With UNION, the database discards a node it has already seen, so each node is expanded once. With UNION ALL and a path, every distinct route is a different row, and the number of routes can grow exponentially even though only 200 nodes exist. In SQL Server, where UNION is not allowed in the recursive member, deduplicate with a visited check or reduce the edges first.