Sub topic 12
What the recursive member may not do
This chapter assumes you can write a basic WITH RECURSIVE query with an anchor member and a recursive member, and that you know how the working table is refilled on each iteration. It also assumes you are comfortable with joins, GROUP BY, and subqueries. The examples run on PostgreSQL and SQLite. Where SQL Server differs, the text says so.
Why the recursive member is restricted
A recursive CTE is not evaluated as a loop that can look at everything produced so far. At each step the engine feeds the recursive member only the rows added by the previous iteration, which is the working table. It runs the member once against those rows, and the output becomes the next working table. The process ends when an iteration produces no rows.
That design only works if each input row can be processed independently of the others. Rows produced earlier must stay valid when later rows arrive. Operations that need the whole set, or that can retract a row once more data shows up, break this guarantee. Database engines forbid them in the recursive member instead of returning wrong results.
The common rules
The exact wording and error messages differ by engine. The rules below hold in most of them.
- The recursive member must refer to the CTE exactly once in its
FROMclause. - The reference must not appear inside a subquery.
- The recursive member must not use aggregate functions,
GROUP BY, orHAVINGover the recursive reference. - The recursive reference must not sit on the nullable side of an outer join.
- The anchor member must not refer to the CTE, and it must come before the recursive member.
- Every column in the recursive member must match the anchor's column in count and type.
Rule 1: one reference only
Joining the CTE to itself, to compare a row with two different earlier levels, is rejected. The working table holds only the last iteration, so a second reference would have no clear meaning. If you need information from earlier levels, carry it forward in columns. A path array, a running total, or a parent-of-parent id are all common choices.
Rule 2: no subquery on the CTE
This is rejected, because the CTE appears inside a subquery:
-- Rejected: the recursive reference is inside a subquery
SELECT e.id, e.name, e.manager_id, c.depth + 1
FROM employees e
JOIN chain c ON c.id = e.manager_id
WHERE e.salary < (SELECT MAX(salary) FROM chain);Subqueries on base tables are fine. A subquery on the CTE is allowed in the outer query, after the recursion has finished.
Rule 3: no aggregation inside the recursion
You cannot write SUM, MAX, COUNT, or GROUP BY over the recursive reference. For example, a query that computes MAX(c.depth) + 1 ... GROUP BY e.id in the recursive member is refused. PostgreSQL reports an error about aggregate functions in the recursive term, and the other engines refuse it too. MySQL and SQLite also reject window functions there. MySQL additionally rejects ORDER BY and, unless you use UNION DISTINCT, DISTINCT. SQL Server also rejects DISTINCT and TOP.
The fix is to turn the aggregate into arithmetic on a carried column. The next section shows this.
Rule 4: outer joins
An outer join on the recursive reference can add a row for "no match", and a later iteration could then contradict it. SQL Server rejects outer joins in the recursive member altogether. PostgreSQL and MySQL reject the recursive reference on the nullable side. If you reach for LEFT JOIN to find rows with no children, move that test to the outer query instead.
Rule 5 and 6: anchor and types
The anchor fixes the column types. This causes the most surprising failures in practice, usually with string paths:
-- Fails in SQL Server, and in PostgreSQL when the anchor column is varchar(n):
-- the path column starts at the anchor's width and the recursive member makes it longer.
SELECT id, name AS path FROM employees WHERE manager_id IS NULL
UNION ALL
SELECT e.id, c.path || '/' || e.name ...Widen the column in the anchor with a cast. In SQL Server the cast is CAST(name AS varchar(400)), and you concatenate with +.
Working within the rules
The following script creates a small table and runs a query that respects every rule. It carries a running salary total down each reporting chain. It then flags leaf employees, the ones with no reports, in the outer query.
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
manager_id INTEGER REFERENCES employees(id),
salary INTEGER NOT NULL
);
INSERT INTO employees (id, name, manager_id, salary) VALUES
(1, 'Ada', NULL, 200),
(2, 'Ben', 1, 120),
(3, 'Cy', 1, 110),
(4, 'Di', 2, 90),
(5, 'Ed', 2, 80);
WITH RECURSIVE chain AS (
SELECT id,
CAST(name AS TEXT) AS path,
salary AS chain_salary,
0 AS depth
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT e.id,
c.path || '/' || e.name,
c.chain_salary + e.salary,
c.depth + 1
FROM employees e
JOIN chain c ON e.manager_id = c.id
)
SELECT c.path,
c.depth,
c.chain_salary,
NOT EXISTS (
SELECT 1 FROM employees x WHERE x.manager_id = c.id
) AS is_leaf
FROM chain c
ORDER BY c.path;This produces five rows. Ada has depth 0, a chain salary of 200, and is not a leaf. Ada/Ben has 320 and is not a leaf. Ada/Ben/Di has 410, Ada/Ben/Ed has 400, and Ada/Cy has 310. These three are leaves. On SQLite, is_leaf prints as 0 or 1.
Three techniques from this query apply broadly:
- Running values replace aggregates.
c.chain_salary + e.salarydoes whatSUMover the ancestors would do. Each row carries its own history, so nothing needs the full set. - The anchor sets the type. The
CAST(name AS TEXT)keeps the path column wide enough for every later concatenation. - Set-wide questions go in the outer query. The
NOT EXISTStest refers to the base table. It could just as well refer tochainitself, because after the recursion finishes the CTE is an ordinary result set.
Per-dialect behavior
| Rule | PostgreSQL | MySQL | SQL Server |
|---|---|---|---|
| Recursive reference more than once | Error | Error | Error |
| Recursive reference in a subquery | Error | Error | Error |
| Aggregate or `GROUP BY` over the recursion | Error | Error | Error |
| Outer join with the recursive reference | Rejected on the nullable side | Rejected on the nullable side | Any outer join rejected |
| `TOP` in the recursive member | Not applicable | Not applicable | Error |
SQLite follows the same pattern as the others. The recursive table must appear once in the FROM clause of the recursive select, must not be in a subquery, and the recursive select cannot use aggregate or window functions. These rules change between versions, so check the documentation for the version you run.
What counts as the "recursive reference"
A few details trip people up:
- Several recursive members. The standard describes one anchor and one recursive member joined by
UNION ALL. Some engines accept several recursive members, and others do not. Do not rely on this when you need portable SQL. - Other CTEs are free to use. You can define a second CTE before the recursive one and join it inside the recursive member. A non-recursive CTE that does not refer to the recursive one is an ordinary table for this purpose.
- Joins to base tables are unrestricted. You can join as many other tables as you like. Only the recursive CTE is limited to one reference.
UNIONinstead ofUNION ALL. PlainUNIONremoves rows already seen. The restrictions above still apply. A previous chapter covers the trade-offs ofUNIONagainstUNION ALL.- Nondeterministic functions. Expressions such as
random()are evaluated per row in each iteration. Their results can vary between runs, and this can affect termination if you test them in the recursiveWHERE.
Checklist when a recursive query errors
- Count the references to the CTE in the recursive member. There must be exactly one, and it must not be in a subquery.
- Search the recursive member for
SUM,COUNT,MAX,GROUP BY,HAVING,DISTINCT,TOP, or window functions. Remove them or move them outside. - Check each join on the recursive reference. Change outer joins to inner joins, or move the "no match" test to the outer query.
- Compare anchor and recursive column types. Add casts in the anchor so that strings and numbers can grow.
- Confirm the recursive member has a termination condition, such as a depth limit or a path check.
Exercise
A recursive member contains LEFT JOIN chain c ON c.id = e.manager_id, and the engine rejects it. The goal is to list every employee together with a flag showing whether they have any reports. Which two changes make the query valid, and where does the "has reports" test belong?
Show answer
First, change the join to an inner join (JOIN chain c ON e.manager_id = c.id), so the recursive reference is no longer on the nullable side of an outer join. Second, remove the "no match" logic from the recursion and compute the flag in the outer query with NOT EXISTS (SELECT 1 FROM employees x WHERE x.manager_id = c.id), or with a LEFT JOIN to the base table after the CTE has finished. The outer query can use outer joins, subqueries, and aggregates without the recursive-member restrictions.
Exercise
You want each row in a recursive CTE to show the total salary of all its ancestors, and you wrote SUM(c.chain_salary) ... GROUP BY e.id in the recursive member. Why is it rejected, and what is the replacement?
Show answer
The recursive member sees only the previous iteration's rows, and aggregates are not allowed over the recursive reference. Carry the total in a column instead. Start with the anchor's own salary and use c.chain_salary + e.salary in the recursive member. Each row then holds the sum along its own chain, with no aggregation inside the recursion.