Sub topic 4
Your first recursive query: generating a series
Assume you already know SELECT, WHERE, ORDER BY, and basic common table expressions (CTEs). A CTE is a named query that you can use like a temporary result set within one SQL statement.
A recursive CTE is useful when each row depends on the row produced immediately before it. Generating a sequence is the smallest useful example. The query below produces the integers from 1 through 10.
WITH RECURSIVE n(i) AS (
SELECT 1
UNION ALL
SELECT i + 1
FROM n
WHERE i < 10
)
SELECT i
FROM n
ORDER BY i;The CTE has two parts:
- The anchor member is
SELECT 1. It creates the first row. - The recursive member is the second
SELECT. It reads rows already produced byn, adds one, and returns the next row. UNION ALLcombines the anchor result with the recursive results.
The column list, n(i), names the CTE and its column. Both members must return the same number of columns with compatible data types. Here, both return one integer.
How the iterations work
The database evaluates the query in rounds. The first round runs the anchor member. Each later round runs the recursive member against the rows from the preceding round.
| Round | Input value | New value |
|---|---|---|
| Anchor | — | 1 |
| 1 | 1 | 2 |
| 2 | 2 | 3 |
| 3 | 3 | 4 |
| ... | ... | ... |
| 9 | 9 | 10 |
| 10 | 10 | none |
When i is 10, the condition i < 10 is false, so that row produces no successor. The query stops and returns all rows collected so far.
Changing the series
To generate a different range, change the anchor and the stopping condition. This query generates even numbers from 2 through 10:
WITH RECURSIVE evens(value) AS (
SELECT 2
UNION ALL
SELECT value + 2
FROM evens
WHERE value < 10
)
SELECT value
FROM evens
ORDER BY value;To generate dates, use a date interval where the database supports interval arithmetic:
WITH RECURSIVE days(day) AS (
SELECT DATE '2026-01-01'
UNION ALL
SELECT day + INTERVAL '1 day'
FROM days
WHERE day < DATE '2026-01-07'
)
SELECT day
FROM days
ORDER BY day;This date example uses PostgreSQL syntax. Other database systems represent date addition differently.
Common errors include forgetting the WHERE condition, changing the column count between the two members, and using a step that moves away from the limit. For example, value + 1 cannot reach a maximum when the starting value is already greater than that maximum unless the query handles that case separately.
Exercise
Modify the integer query to generate the values 5, 10, 15, 20, and 25.
Show answer
Use SELECT 5 as the anchor, SELECT value + 5 FROM series, and WHERE value < 25 in the recursive member.