Sub topic 2
Anatomy of a recursive CTE
This chapter assumes you can write SELECT queries with WHERE, ORDER BY, joins and self-joins, and that you have used a plain WITH clause. It covers the parts of a recursive common table expression (CTE) and the rules that tie them together. The next chapter covers how the database runs them.
What makes a CTE recursive
A plain CTE is a named subquery. It runs once, and the main query reads its result. A recursive CTE differs in one way: its own definition refers to its own name. That self-reference lets one query keep producing rows from rows it already produced.
Every recursive CTE has the same three parts:
- The anchor member. This is a query that does not refer to the CTE. It produces the starting rows.
- The recursive member. This is a query that does refer to the CTE. It produces new rows from rows already found.
- The combiner. This is a set operator, usually
UNION ALL, that joins the two members into one result.
The smallest useful example generates the numbers 1 through 10:
WITH RECURSIVE n(i) AS (
SELECT 1 -- anchor member
UNION ALL
SELECT i + 1 FROM n WHERE i < 10 -- recursive member
)
SELECT i FROM n;The anchor yields one row, 1. The recursive member reads n, adds one to i, and stops producing rows once i reaches 10. The outer SELECT then reads the combined result: the numbers 1 through 10.
The syntax, piece by piece
WITH RECURSIVE cte_name (col1, col2, ...) AS (
<anchor query>
UNION ALL
<recursive query that mentions cte_name>
)
<main query that reads cte_name>;RECURSIVEis required in PostgreSQL, MySQL 8, and SQLite. SQL Server does not use the keyword. A bareWITHhandles both plain and recursive CTEs there, and Oracle works the same way. The dialect chapter covers this in detail.- The column list after the name is optional. Without it, the column names come from the anchor query. Listing them is clearer, and some databases need it when the anchor uses unnamed expressions.
- The anchor must come first, and it must not mention the CTE name.
- The recursive member must mention the CTE name, usually in its
FROMclause.
The following diagram shows how the pieces connect:
The loop between the recursive member and the result is the recursion. The anchor sits outside the loop and runs once.
The anchor member
The anchor member answers the question "where do we start?" It is an ordinary query, and it can be as complex as you like, with joins, filters, and aggregates, as long as it does not refer to the CTE.
In the number example the anchor is a constant. In a hierarchy it is usually a filter that finds the root:
WITH RECURSIVE chain AS (
SELECT id, name, manager_id, 0 AS depth
FROM employees
WHERE manager_id IS NULL -- anchor: the top of the tree
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 member
)
SELECT id, name, depth
FROM chain
ORDER BY depth, name;Here the anchor selects the employee with no manager. It also creates a depth column starting at 0. That column is how the recursion carries information forward from one step to the next.
An anchor can return many rows. If you filtered with WHERE manager_id = 7, the recursion would start from every direct report of employee 7. It would then walk down from each of them.
The recursive member
The recursive member answers the question "given the rows we just found, what is the next set of rows?" It normally joins the CTE to a base table. In the org chart, the join condition e.manager_id = c.id says: find employees whose manager is a row we already have.
Three habits keep recursive members correct:
- Put the CTE on one side of a join and a base table on the other. The CTE supplies the rows you have. The base table supplies the rows you want to reach.
- Compute the next state from the current one.
i + 1andc.depth + 1both build on the values from the row just read. - Include a way to stop. A
WHEREfilter, or a join that eventually matches nothing, is what ends the recursion.
The recursive member does not see the whole result so far. At each step it sees only the rows added by the previous step. The execution chapter explains this. For now, remember that the FROM n in the series example does not re-read all earlier numbers.
Column types and names
The anchor member decides the column names and, in most databases, the data types of the whole CTE. The recursive member has to produce the same number of columns, in the same order, with compatible types.
This matters when a value grows as the recursion goes. Consider building a text path:
- SQL Server raises an error if the anchor and recursive member disagree on type or length, for example
varchar(10)against a longer string. - MySQL can reject a row with a "Data too long" error when the recursive member produces a string wider than the anchor's column.
The usual fix is to cast the anchor to a wide enough type:
WITH RECURSIVE path_demo (n, label) AS (
SELECT 1, CAST('a' AS VARCHAR(100))
UNION ALL
SELECT n + 1, CAST(label || 'a' AS VARCHAR(100))
FROM path_demo
WHERE n < 5
)
SELECT n, label FROM path_demo;This runs in PostgreSQL and SQLite as written. MySQL does not support the || string operator by default and needs CONCAT(label, 'a'). SQL Server needs + and no RECURSIVE keyword. Casting the anchor to VARCHAR(100) gives the label room to grow in each of them.
UNION ALL, and why UNION is different
The combiner joins the anchor rows and the recursive rows into one result. UNION ALL keeps every row. UNION removes duplicates. PostgreSQL, MySQL, and SQLite accept both.
Use UNION ALL by default. It is cheaper because the database does not compare each new row against earlier ones. Plain UNION can also stop a recursion that would otherwise repeat forever, but only when the repeated rows are fully identical. A depth or path column that changes every step defeats that. A later chapter covers this in detail.
SQL Server allows only UNION ALL as the combiner in a recursive CTE.
What the recursive member may not do
Databases restrict what a recursive member can contain, because the engine has to evaluate it one step at a time. The exact list varies by product. Common restrictions include:
- The CTE name may appear only once in the recursive member in many databases, including MySQL and SQL Server.
- The CTE name may not appear inside a subquery in many databases.
- Aggregates,
DISTINCT, andGROUP BYover the recursive reference are often not allowed. - The CTE name may not be on the nullable side of an outer join. A
LEFT JOINwith the CTE on the right is generally rejected.
The restrictions chapter covers these in full. If you see an error such as "recursive reference must not appear within...", check this list first.
A worked example
This query builds the first eight powers of two and shows each of the parts:
WITH RECURSIVE powers (exp, value) AS (
SELECT 0, 1 -- anchor: 2^0 = 1
UNION ALL
SELECT exp + 1, value * 2 -- recursive member
FROM powers
WHERE exp < 7 -- stopping condition
)
SELECT exp, value FROM powers ORDER BY exp;| exp | value |
|---|---|
| 0 | 1 |
| 1 | 2 |
| 2 | 4 |
| 3 | 8 |
| 4 | 16 |
| 5 | 32 |
| 6 | 64 |
| 7 | 128 |
Reading the query in order:
- The anchor contributes the row
(0, 1). - The recursive member reads that row, tests
exp < 7, and produces(1, 2). - The member repeats on each newly produced row. When it reads
(7, 128), the testexp < 7fails and no new row appears. - With no new rows, the recursion ends, and the main query returns all eight rows.
Common mistakes
- Referring to the CTE in the anchor. The anchor must stand alone. Otherwise there is nothing to start from.
- Forgetting
RECURSIVE. On PostgreSQL, MySQL, and SQLite the query fails or does not run as recursion. On SQL Server, adding the keyword is the error. - Mismatched column lists. The anchor and recursive member must return the same number of columns in the same order.
- Putting the stopping filter in the outer query. A
WHERE i < 10in the finalSELECTdoes not stop the recursion. It only hides rows afterward, and the recursion itself still runs without end. The condition belongs inside the recursive member. - Using the wrong join direction. In the org chart,
e.manager_id = c.idwalks down to reports. Swapping the sides toe.id = c.manager_idwalks up to managers.
Exercise
Given the query below, list every value of v it returns and say which part of the query ends the recursion.
WITH RECURSIVE t (v) AS (
SELECT 3
UNION ALL
SELECT v * 2 FROM t WHERE v < 20
)
SELECT v FROM t;
Show answer
It returns 3, 6, 12, and 24. The anchor supplies 3. Each recursive step doubles the previous value while that value is below 20: 3 produces 6, 6 produces 12, and 12 produces 24. When the recursive member reads 24, the filter v < 20 is false, so it produces no rows and the recursion ends. The last value, 24, is above 20 because the filter tests the row being read, not the row being produced.
Exercise
A colleague writes a recursive CTE whose anchor query is SELECT id FROM categories WHERE id IN (SELECT id FROM tree), where tree is the CTE being defined. What is wrong, and how would you fix it?
Show answer
The anchor refers to the CTE itself, but the anchor must not. It has to be a query that runs on its own to supply the starting rows. Move the self-reference into the recursive member, and make the anchor select the root rows from the base table, for example SELECT id FROM categories WHERE parent_id IS NULL.