Sub topic 5
Recursive CTEs: Anchor Member, Recursive Member, and UNION ALL
This chapter assumes you can write a basic WITH clause, you know how JOIN and UNION ALL work, and you have met the idea of a CTE name being visible only inside one statement. The examples run on PostgreSQL. Other dialects differ in small ways, and a later chapter covers those differences.
Why recursion is needed
A normal CTE is evaluated once and cannot refer to itself. Some questions need a query to keep going until it runs out of new rows:
- Who reports to whom, at any depth, in an employee table?
- Which categories sit below "Electronics" in a category tree?
- Which nodes can be reached from node 1 in a graph?
- What are the numbers 1 to 100, or every date in a month?
You cannot write these with a fixed number of joins, because you do not know the depth in advance. A recursive CTE handles them. It is a CTE whose definition refers to its own name.
The shape of a recursive CTE
A recursive CTE has two parts joined by UNION ALL:
- The anchor member is a query that does not refer to the CTE. It produces the starting rows.
- The recursive member is a query that does refer to the CTE. It takes the rows produced so far and produces new rows from them.
Here is the smallest useful example.
WITH RECURSIVE numbers(n) AS (
SELECT 1
UNION ALL
SELECT n + 1 FROM numbers WHERE n < 5
)
SELECT n FROM numbers;The result is the numbers 1, 2, 3, 4, 5.
WITH RECURSIVEtells the engine that at least one CTE in the list refers to itself. PostgreSQL and MySQL require the keywordRECURSIVE. SQL Server and Oracle do not use it.numbers(n)names the CTE and its column. Listing the column names is optional, but it is common in recursive CTEs because the column names come from the anchor member.SELECT 1is the anchor member.SELECT n + 1 FROM numbers WHERE n < 5is the recursive member. It reads fromnumbers, the CTE being defined.UNION ALLcombines the anchor rows and every batch of recursive rows into one result.
How the engine evaluates it
The engine does not call the query recursively in the programming sense. It runs a loop, and each pass works only on the rows added by the previous pass.
- Run the anchor member. Put its rows in the result and also in a working table, which holds the rows the next step will read.
- Run the recursive member. Each time it mentions the CTE name, that name means the working table, not the whole result so far.
- Add the rows from step 2 to the result. Replace the working table with just those new rows.
- Repeat steps 2 and 3. Stop when the recursive member returns no rows.
For the numbers example, the passes look like this.
| Pass | Working table before | Recursive member returns | Result so far |
|---|---|---|---|
| Anchor | (none) | 1 | 1 |
| 1 | 1 | 2 | 1, 2 |
| 2 | 2 | 3 | 1, 2, 3 |
| 3 | 3 | 4 | 1, 2, 3, 4 |
| 4 | 4 | 5 | 1, 2, 3, 4, 5 |
| 5 | 5 | nothing, because `5 < 5` is false | stop |
The key point is that the recursive member sees only the previous pass's rows. That is why n + 1 adds one to a single value each time instead of to the growing set.
Why UNION ALL
Almost all recursive CTEs use UNION ALL. UNION (without ALL) removes duplicate rows, and that has two consequences.
- It costs extra work, because the engine must compare each new row with the rows it already has.
- In some databases it changes how the loop can end. PostgreSQL allows
UNIONin a recursive CTE, and a row that has already been produced is discarded, so a cycle that repeats an identical row will stop. SQL Server and several other engines requireUNION ALL.
Use UNION ALL unless you have a specific reason not to. It is portable and fast. If you need to avoid repeated paths, use an explicit guard, which is the subject of the next chapter.
A recursive CTE over a table: the org chart
Recursion becomes useful when the recursive member joins the CTE to a real table. Take an employees table where manager_id points to another row's id, and the top person has manager_id set to NULL.
WITH RECURSIVE org 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, o.depth + 1
FROM employees e
JOIN org o ON e.manager_id = o.id
)
SELECT id, name, depth
FROM org
ORDER BY depth, name;Read it as two instructions:
- Anchor: start with the employee who has no manager. Give that row depth 0.
- Recursive: for the rows found in the last pass, find every employee whose
manager_idequals one of those rows'id. Give each one a depth of its manager's depth plus one.
Suppose the data is:
| id | name | manager_id |
|---|---|---|
| 1 | Ava | NULL |
| 2 | Ben | 1 |
| 3 | Chen | 1 |
| 4 | Dara | 2 |
The anchor returns Ava at depth 0. The first recursive pass finds employees whose manager is 1: Ben and Chen at depth 1. The second pass finds employees whose manager is 2 or 3: Dara at depth 2. The third pass finds no one whose manager is 4, so the loop stops.
Notice that the join condition runs from the child's foreign key to the CTE's key: e.manager_id = o.id. To walk downward from a parent to its children, match the child's pointer to the parent's id. To walk upward from a child to its ancestors, reverse the logic: start at one employee and join e.id = o.manager_id.
Rules for the two members
Engines are strict about the structure of a recursive CTE. The exact limits vary, but these rules hold in PostgreSQL and are close to what other databases enforce.
- The anchor member must come first and must not refer to the CTE.
- The recursive member must refer to the CTE exactly once in its
FROMclause. Referring to it twice, for example in a self-join of the CTE, is rejected. - The recursive reference cannot appear inside a subquery in the recursive member in most engines. Use a join instead.
- The recursive reference usually cannot be on the nullable side of an outer join. A
LEFT JOINwith the CTE on the right side fails in PostgreSQL. - Aggregate functions,
DISTINCT, and window functions in the recursive member are restricted or rejected, because the member must work row by row on the working table. - Column types must match between the two members. The types come from the anchor member.
That last rule causes a common surprise. The anchor decides the type and length of each column, and the recursive member must fit.
WITH RECURSIVE bad(label) AS (
SELECT 'a'::varchar(1)
UNION ALL
SELECT label || 'b' FROM bad WHERE length(label) < 4
)
SELECT label FROM bad;Depending on the database and version, this fails or truncates, because the anchor fixed the column at one character and the recursive member produces longer strings. PostgreSQL reports a type mismatch for this example. The fix is to cast the anchor to a wide enough type, such as SELECT 'a'::text.
WITH RECURSIVE good(label) AS (
SELECT 'a'::text
UNION ALL
SELECT label || 'b' FROM good WHERE length(label) < 4
)
SELECT label FROM good;This returns a, ab, abb, and abbb.
Building a path as you go
Because each pass can add columns computed from the previous row, a recursive CTE can carry information down the tree. A common use is building a readable path.
WITH RECURSIVE org AS (
SELECT id, name, manager_id, name::text AS path
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT e.id, e.name, e.manager_id, o.path || ' > ' || e.name
FROM employees e
JOIN org o ON e.manager_id = o.id
)
SELECT path FROM org ORDER BY path;With the sample data, the output is:
AvaAva > BenAva > Ben > DaraAva > Chen
The anchor casts name to text so that the column is wide enough for the longer paths added later.
Order of results
A recursive CTE has no guaranteed output order. Rows tend to come out in the order they were produced, which is breadth-first: all of one level, then all of the next. Do not depend on it. If order matters, add ORDER BY to the outer query, as the examples above do. To get a depth-first order, sort by a path column, such as the array or text path shown above.
What can go wrong
If the recursive member keeps returning rows, the loop never ends. Two causes are common.
- A missing stop condition, such as removing
WHERE n < 5from the numbers example. - Data that contains a cycle, such as employee A managed by B and B managed by A.
WITH RECURSIVE forever(n) AS (
SELECT 1
UNION ALL
SELECT n + 1 FROM forever
)
SELECT n FROM forever LIMIT 5;In PostgreSQL this particular query does return five rows, because the outer LIMIT lets the engine stop reading. Without the LIMIT, it runs until memory or disk runs out or the statement is cancelled. Do not rely on LIMIT as a safety net for real queries, because it only helps when the outer query can stop early, and behavior differs between engines.
Some databases also impose their own ceiling. SQL Server stops after 100 recursion levels by default and reports an error unless you raise the limit with OPTION (MAXRECURSION n). PostgreSQL has no default level limit.
A quick checklist
Before running a recursive CTE, check each item.
- The anchor member returns the right starting rows and does not mention the CTE.
- The recursive member mentions the CTE once and joins it to the table that holds the next level.
- The join runs in the right direction: down the tree or up it.
- The column types set by the anchor are wide enough for every later row.
- Something ends the recursion: a condition, a finite tree, or a guard.
- The outer query has an
ORDER BYif order matters.
Exercise
A table categories(id, name, parent_id) stores a tree, and the root has parent_id NULL. Write a recursive CTE that lists every category with its depth, where the root has depth 1. Then explain what the recursive member sees on its second pass.
Show answer
WITH RECURSIVE tree AS ( SELECT id, name, parentid, 1 AS depth FROM categories WHERE parentid IS NULL UNION ALL SELECT c.id, c.name, c.parentid, t.depth + 1 FROM categories c JOIN tree t ON c.parentid = t.id ) SELECT id, name, depth FROM tree ORDER BY depth, name; On its second pass, the recursive member reads only the rows produced by the first recursive pass (the categories at depth 2), not the anchor row and not the full result so far. It therefore finds the depth 3 categories whose parent_id matches one of those rows.
Exercise
Why does the following query fail or misbehave in PostgreSQL, and how do you fix it? WITH RECURSIVE r(s) AS ( SELECT 'x'::varchar(1) UNION ALL SELECT s || 'y' FROM r WHERE length(s) < 3 ) SELECT s FROM r;
Show answer
The anchor member fixes the column type as varchar(1), and the recursive member produces longer strings, so the types do not match. Fix it by casting the anchor to a wider type, for example SELECT 'x'::text. The query then returns x, xy, and xyy.