Sub topic 2
Anatomy of a Recursive CTE
This chapter assumes you know SELECT, WHERE, ORDER BY, inner joins, self-joins, GROUP BY, and basic subqueries. A recursive common table expression (CTE) is a named query that refers to itself. It lets SQL repeat a step until that step produces no more rows.
The three parts
A recursive CTE has three important parts:
- The anchor member produces the starting rows.
- The recursive member produces more rows by reading rows already found.
UNION ALLcombines the starting rows with the rows produced by recursion.
The recursive member must return the same number of columns as the anchor member. The matching columns should also have compatible data types.
WITH RECURSIVE n(i) AS (
SELECT 1
UNION ALL
SELECT i + 1
FROM n
WHERE i < 10
)
SELECT i
FROM n;The CTE is named n, and it has one column named i.
- The anchor member is
SELECT 1. - The recursive member is
SELECT i + 1 FROM n WHERE i < 10. - The final query reads the complete result from
n.
The result is the numbers 1 through 10.
How the database evaluates it
The database evaluates the query in rounds. It first runs the anchor member. Those rows become both the initial result and the first working table, which is the temporary set used by the next round.
Then the database runs the recursive member against the current working table. The rows it produces are added to the result and become the working table for the next round.
This continues until the recursive member returns no rows.
For the number query, the rounds look like this:
| Round | Working row | New row |
|---|---|---|
| Anchor | 1 | 1 |
| 1 | 1 | 2 |
| 2 | 2 | 3 |
The process continues until i is 10. At that point, WHERE i < 10 is false, so no row is produced for the next round.
The working table describes the logical evaluation model. A database may use different internal plans, but the query must behave as if it followed these rounds.
Why `UNION ALL` matters
UNION ALL keeps every row produced by every round. It is usually the natural choice for sequences, trees, and paths.
Plain UNION removes duplicate rows. That can stop some recursive queries when a repeated row would otherwise continue appearing, but it can also hide meaningful duplicates and add duplicate-removal work. Do not use it as a replacement for a clear stopping condition.
A recursive query needs a condition that makes progress toward termination. In the example, i increases while the condition allows it. Without WHERE i < 10, the query would keep generating numbers until the database's recursion safeguard stopped it.
Exercise
Exercise
In the query below, which part is the anchor member, and what values will the query return? WITH RECURSIVE n(i) AS ( SELECT 5 UNION ALL SELECT i - 1 FROM n WHERE i > 2 ) SELECT i FROM n;
Show answer
The anchor member is SELECT 5. The recursive member subtracts one while i > 2, so the result is 5, 4, 3, and 2.