Sub topic 3
How the database evaluates a recursive CTE
This chapter assumes you can write a basic WITH query, self-join a table, and read a UNION ALL. You do not need to have written a recursive query before. The goal is to learn what the database does at each step, so you can predict a recursive query's output and cost before you run it.
The algorithm in one paragraph
A recursive common table expression (CTE) has an anchor member and a recursive member joined by UNION ALL. The database does not run it as a function that calls itself. It runs a loop.
- Run the anchor member once. Put its rows into the result and into a working table.
- Run the recursive member. Wherever it mentions the CTE's own name, it reads the working table. It does not read the whole result so far.
- If the recursive member returned no rows, stop.
- Otherwise, append the new rows to the result. Make them the new working table, replacing the old one. Go back to step 2.
- When the loop ends, the outer query reads the accumulated result.
The working table is a temporary buffer that holds only the rows produced by the most recent iteration. The recursive reference sees one "generation" at a time. This one fact explains most of the rules and surprises in this chapter.
A traced example
Create a small org chart and run a traversal that records which iteration produced each row.
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
manager_id INTEGER REFERENCES employees (id)
);
INSERT INTO employees (id, name, manager_id) VALUES
(1, 'Ada', NULL),
(2, 'Ben', 1),
(3, 'Cara', 1),
(4, 'Dev', 2),
(5, 'Eli', 2),
(6, 'Fay', 4);
WITH RECURSIVE chain AS (
SELECT id, name, 0 AS iteration
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT e.id, e.name, c.iteration + 1
FROM employees e
JOIN chain c ON e.manager_id = c.id
)
SELECT iteration, id, name
FROM chain
ORDER BY iteration, id;The database evaluates this as follows.
| Step | Working table read by the recursive member | Rows the member returns | Result so far |
|---|---|---|---|
| Anchor | none | Ada | Ada |
| 1 | Ada | Ben, Cara (managed by Ada) | Ada, Ben, Cara |
| 2 | Ben, Cara | Dev, Eli (managed by Ben; Cara has no reports) | Ada, Ben, Cara, Dev, Eli |
| 3 | Dev, Eli | Fay (managed by Dev) | all six employees |
| 4 | Fay | nothing | all six employees |
Step 4 returns zero rows, so the loop ends. Notice that the join in step 2 never looked at Ada. The join e.manager_id = c.id compared employees only with Ben and Cara. This is why the pattern scales: each iteration touches only the frontier, not everything found earlier.
The same loop in Python
If you prefer code to prose, this script is a faithful model of the process. It runs as written and prints the same iterations.
employees = [
(1, "Ada", None),
(2, "Ben", 1),
(3, "Cara", 1),
(4, "Dev", 2),
(5, "Eli", 2),
(6, "Fay", 4),
]
# Anchor member: runs once.
working = [(i, name, 0) for (i, name, mgr) in employees if mgr is None]
result = []
while working:
result.extend(working)
# Recursive member: reads only the working table.
working = [
(i, name, w_iter + 1)
for (w_id, _, w_iter) in working
for (i, name, mgr) in employees
if mgr == w_id
]
for iteration, row in sorted(((r[2], r) for r in result)):
print(iteration, row[0], row[1])The line working = [...] is the replacement step. The old working table is discarded, and result keeps everything.
What this model explains
Why the recursive member sees only one generation
Suppose you wanted the recursive member to compare each new row against every row found so far, for example to skip duplicates. The working table does not contain those older rows, so the member cannot do that. This is a design limit of the evaluation model, not a bug. Duplicate handling and cycle handling are done another way, covered in the chapters on UNION versus UNION ALL and on cycle detection.
Why the stop condition is "no new rows"
The loop ends when an iteration returns nothing. It does not end when the data "runs out" in any other sense. A query terminates only if the recursive member eventually produces an empty set. In a tree, leaves have no children, so every branch dries up. In a graph with a cycle, the frontier never empties, because the loop keeps finding the same nodes again. An explicit condition such as WHERE i < 10 forces the empty set. The chapter on termination covers the options in full.
Why the anchor runs exactly once
The anchor member contains no reference to the CTE. It is an ordinary query evaluated one time to seed the loop. If you need several starting points, such as every top-level employee, the anchor returns several rows and the loop processes them together, one generation at a time.
Why row order is not guaranteed
In practice, most databases return rows in the order they were generated, so you often see a breadth-first listing: all of iteration 0, then iteration 1, and so on. The SQL standard does not promise this. If order matters, sort in the outer query, as the example does with ORDER BY iteration, id. For a depth-first listing, carry a path column and sort by it. That technique appears in the next chapters.
Linear recursion and the single reference
Most databases require the recursive member to mention the CTE exactly once, in its FROM clause. This is called linear recursion. It matches the model: one working table, read once per iteration. A query that joined the CTE to itself inside the recursive member would need two copies of the working table, and the standard and most engines reject it. The chapter on restrictions lists what else is forbidden, such as aggregates and LEFT JOIN with the CTE on the nullable side. Most of those rules follow from the same idea. The recursive member must be safe to run on a small slice of rows, repeatedly.
Laziness and early stopping
Some engines evaluate the loop lazily. PostgreSQL produces rows only as the parent query asks for them. An unbounded CTE with an outer LIMIT therefore stops:
WITH RECURSIVE n(i) AS (
SELECT 1
UNION ALL
SELECT i + 1 FROM n
)
SELECT i FROM n LIMIT 5;This returns the numbers 1 to 5 in PostgreSQL. It is an implementation behavior and not a portable guarantee. Other databases may run the loop until a recursion limit trips, and a planner change could alter the behavior. Put the bound in the recursive member's WHERE clause if you want a query that is correct everywhere.
Cost follows the loop
Total work is roughly the sum of the work in each iteration. Each iteration performs one join between the working table and a base table.
- The number of iterations equals the depth of the data (the longest chain), plus one final empty pass. A tree 4 levels deep runs 5 recursive passes.
- The rows per iteration equal the size of that generation. A wide, shallow tree has few big iterations. A long chain has many tiny ones.
- Each iteration's join benefits from an index on the join column. In the org chart, an index on
employees (manager_id)turns each pass into index lookups for the frontier's ids, instead of a scan of the whole table per pass.
Some engines also store the result in a temporary table or spill it to disk when it grows large. A query that returns millions of rows pays for that storage even if the outer query uses only a few columns. Filter early, and avoid carrying wide columns through the recursion. The dedicated performance chapter returns to this.
Dialect notes on the loop
The shape of the algorithm is the same everywhere. These details differ.
| Database | Keyword | Built-in loop guard |
|---|---|---|
| PostgreSQL | `WITH RECURSIVE` | none, so the query runs until it ends or you cancel it |
| MySQL 8 | `WITH RECURSIVE` | `cte_max_recursion_depth`, default 1000, raises an error when exceeded |
| SQLite | `WITH RECURSIVE` | none |
| SQL Server | `WITH`, with no `RECURSIVE` | `MAXRECURSION`, default 100, raises an error when exceeded |
SQLite implements the working table as a queue. It lets an ORDER BY inside the recursive member control which queued row is processed next, which changes the traversal order. The other engines do not offer this.
Common mistakes
- Expecting the member to see all earlier rows. It sees only the previous iteration's output. A condition such as "skip anything already found" does not work in the recursive
WHEREclause. - Forgetting that the anchor runs once. Filters on the anchor choose the roots. Filters on the recursive member prune branches, and that removes everything beneath them.
- Mixing up the two loop endings. A query that errors on a recursion limit and a query that finishes normally are different outcomes. A limit error means the data (or your bound) allowed more iterations than the engine permits. It does not mean the answer was cut short quietly.
- Assuming output order. See the warning above.
Exercise
Using the employees table from this chapter, you change the anchor member to WHERE id IN (2, 3) (Ben and Cara) and keep the recursive member unchanged. List the rows that the working table holds at each iteration, and say how many recursive passes run, including the final empty one.
Show answer
Anchor: working table = Ben, Cara. Pass 1 reads Ben and Cara and returns Dev and Eli (Cara has no reports), so the working table = Dev, Eli. Pass 2 reads Dev and Eli and returns Fay, so the working table = Fay. Pass 3 reads Fay and returns nothing, so the loop ends. Three recursive passes run, including the final empty one. The result is Ben, Cara, Dev, Eli, Fay. Ada is absent because the loop only follows manager links downward from the anchor rows.
Exercise
A colleague says that a recursive CTE can detect cycles by adding WHERE e.id NOT IN (SELECT id FROM chain) to the recursive member. Why does this not work in the evaluation model described here?
Show answer
The reference to chain inside the recursive member reads only the working table, which holds the previous iteration's rows. It does not hold every row found so far. A node that was found two or more iterations ago is not in that table, so the check cannot see it, and the cycle continues. (Most engines also reject a second reference to the CTE inside the recursive member.) Cycle detection needs information carried along each row, such as a path array, which the cycle chapter covers.