27. WITH RECURSIVE: a step that uses itself
Count, make a run of dates, and walk a tree: a CTE that feeds its own rows back into itself, and how to make sure it stops.
Counting from 1 to 10
In the last chapter each step of a WITH used the steps before it. With WITH RECURSIVE, a step can use itself: it starts from some rows, and from each new row makes the next ones. The smallest example counts from 1 to 10, with no table at all:
WITH RECURSIVE n(x) AS (
SELECT 1
UNION ALL
SELECT x + 1 FROM n WHERE x < 10
)
SELECT x FROM n;| x |
|---|
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
| 8 |
| 9 |
| 10 |
A recursive CTE always has two parts joined by UNION ALL:
- The start (before
UNION ALL):SELECT 1. It runs once and gives the first rows. - The step (after
UNION ALL):SELECT x + 1 FROM n WHERE x < 10. It names the CTE itself (FROM n), and makes new rows from rows already made.
How it runs, step by step
The database keeps a queue of rows waiting to be used:
- Run the start. It gives
1: put it in the result and in the queue. - Take the first row out of the queue (
x = 1) and run the step withnholding just that row. It gives2: into the result and the queue. - Take
2out, run the step: it gives3. And so on. - At
x = 10the step'sWHERE x < 10is false, so it gives nothing. Nothing new goes into the queue. - The queue is empty: the CTE is finished, with the 10 rows it made.
| Row taken | The step gives | Queue after |
|---|---|---|
| (start) | 1 | 1 |
| 1 | 2 | 2 |
| 2 | 3 | 3 |
| ... | ... | ... |
| 9 | 10 | 10 |
| 10 | nothing (10 < 10 is false) | empty: stop |
The step sees only the row just taken, not everything made so far. A row can carry along anything it needs, in more columns. Here each row also carries a running total, so the last row holds 1 + 2 + ... + 10:
WITH RECURSIVE n(x, total) AS (
SELECT 1, 1
UNION ALL
SELECT x + 1, total + x + 1 FROM n WHERE x < 10
)
SELECT x, total FROM n;| x | total |
|---|---|
| 1 | 1 |
| 2 | 3 |
| 3 | 6 |
| 4 | 10 |
| 5 | 15 |
| 6 | 21 |
| 7 | 28 |
| 8 | 36 |
| 9 | 45 |
| 10 | 55 |
A run of dates
Counting is handy for making rows that aren't in any table. A common need: a report with one row for every day, including days with no orders. A GROUP BY on orders can't give those days; it only knows the days that have orders. So make the days first, then join the orders to them:
WITH RECURSIVE day(d) AS (
SELECT '2026-11-01'
UNION ALL
SELECT date(d, '+1 day') FROM day WHERE d < '2026-11-10'
)
SELECT day.d, COUNT(o.id) AS orders
FROM day LEFT JOIN orders AS o ON o.ordered = day.d
GROUP BY day.d
ORDER BY day.d;| d | orders |
|---|---|
| 2026-11-01 | 0 |
| 2026-11-02 | 1 |
| 2026-11-03 | 0 |
| 2026-11-04 | 0 |
| 2026-11-05 | 1 |
| 2026-11-06 | 0 |
| 2026-11-07 | 0 |
| 2026-11-08 | 0 |
| 2026-11-09 | 0 |
| 2026-11-10 | 0 |
10 days, and every one is there: 1 order on the 2nd, 1 on the 5th, and 0 on the other eight. date(d, '+1 day') (chapter 8) does the counting; with '+7 days' or '+1 month' you get weeks or months the same way.
SQLite has no generate_series(), and neither has Phai SQL. A recursive CTE like the ones above is the way to make a run of numbers or dates.
A tree: the shop's staff
Where recursion really shines is a tree: rows that point at other rows of the same table. The shop's staff, each with a boss (boss_id points back into the same table; the owner has no boss):
CREATE TABLE staff (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
role TEXT NOT NULL,
boss_id INTEGER REFERENCES staff(id)
);
INSERT INTO staff VALUES
(1, 'Pranee', 'owner', NULL),
(2, 'Dao', 'shop manager', 1),
(3, 'Ton', 'stock keeper', 1),
(4, 'Nok', 'cashier', 2),
(5, 'Beam', 'barista', 2),
(6, 'Mew', 'trainee barista', 5),
(7, 'Golf', 'driver', 3);A JOIN of staff with itself finds each person's boss, one level up. But how many levels does the tree have? It could be two or twenty, and a query with a fixed number of joins can't know. A recursive CTE goes down as far as the tree goes. Start from the owner (no boss); the step finds the people whose boss is a row just found:
WITH RECURSIVE tree(id, name, depth, path) AS (
SELECT id, name, 0, name FROM staff WHERE boss_id IS NULL
UNION ALL
SELECT s.id, s.name, t.depth + 1, t.path || ' > ' || s.name
FROM staff AS s JOIN tree AS t ON s.boss_id = t.id
)
SELECT depth, name, path FROM tree ORDER BY path;| depth | name | path |
|---|---|---|
| 0 | Pranee | Pranee |
| 1 | Dao | Pranee > Dao |
| 2 | Beam | Pranee > Dao > Beam |
| 3 | Mew | Pranee > Dao > Beam > Mew |
| 2 | Nok | Pranee > Dao > Nok |
| 1 | Ton | Pranee > Ton |
| 2 | Golf | Pranee > Ton > Golf |
Each row carries two things down with it: depth, how many levels below the owner (one more than its boss's), and path, the chain of names from the top (its boss's path plus its own name). Sorting by path puts each person right under their boss, like an outline.
Starting somewhere else gives part of the tree. Everyone under Dao (id 2), Dao included:
WITH RECURSIVE team(id, name, role) AS (
SELECT id, name, role FROM staff WHERE id = 2
UNION ALL
SELECT s.id, s.name, s.role
FROM staff AS s JOIN team AS t ON s.boss_id = t.id
)
SELECT name, role FROM team ORDER BY id;| name | role |
|---|---|
| Dao | shop manager |
| Nok | cashier |
| Beam | barista |
| Mew | trainee barista |
And the tree can be climbed up as well: turn the join around and follow boss_id. Mew's bosses, all the way to the top:
WITH RECURSIVE up(id, name, boss_id, level) AS (
SELECT id, name, boss_id, 0 FROM staff WHERE name = 'Mew'
UNION ALL
SELECT s.id, s.name, s.boss_id, u.level + 1
FROM staff AS s JOIN up AS u ON s.id = u.boss_id
)
SELECT level, name FROM up ORDER BY level;| level | name |
|---|---|
| 0 | Mew |
| 1 | Beam |
| 2 | Dao |
| 3 | Pranee |
The same shape fits every tree: categories inside categories, folders, the parts of a product, replies to replies.
Stopping safely
A recursive CTE stops only when the step gives no new rows. If it always gives one, it never stops: the query runs until it runs out of memory. Two ways to make sure it ends:
- A test in the step's
WHERE, as every example above has:WHERE x < 10,WHERE d < '2026-11-10'. In a tree, a level limit:WHERE t.depth < 20. LIMITinside the CTE, as a safety net. The CTE stops as soon as it has made that many rows, even with no test at all:
WITH RECURSIVE n(x) AS (
SELECT 1
UNION ALL
SELECT x + 1 FROM n
LIMIT 5
)
SELECT x FROM n;| x |
|---|
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
Trees need extra care, because the data itself can make a loop. Suppose someone sets the owner's boss to Mew by mistake. Then Mew's boss is Beam, Beam's is Dao, Dao's is Pranee, Pranee's is Mew... and climbing up never ends. A level limit keeps the query safe:
UPDATE staff SET boss_id = 6 WHERE id = 1;
WITH RECURSIVE up(id, name, boss_id, level) AS (
SELECT id, name, boss_id, 0 FROM staff WHERE name = 'Mew'
UNION ALL
SELECT s.id, s.name, s.boss_id, u.level + 1
FROM staff AS s JOIN up AS u ON s.id = u.boss_id
WHERE u.level < 6
)
SELECT level, name FROM up ORDER BY level;| level | name |
|---|---|
| 0 | Mew |
| 1 | Beam |
| 2 | Dao |
| 3 | Pranee |
| 4 | Mew |
| 5 | Beam |
| 6 | Dao |
The names come round again (Mew at level 0 and level 4): a sure sign of a loop in the data. Put the owner back:
UPDATE staff SET boss_id = NULL WHERE id = 1;A LIMIT on the outer SELECT stops the CTE too, when that SELECT reads the CTE's rows directly, in the order they are made: the database makes them one at a time and stops once it has enough:
WITH RECURSIVE n(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM n)
SELECT x FROM n LIMIT 5;| x |
|---|
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
Don't lean on the outer LIMIT alone. When the outer query must see every row before it answers (an ORDER BY, count(), sum()), the database has to make the whole CTE first, and an endless one runs on and on. A stop inside the CTE (a WHERE in the step, or LIMIT inside the brackets) is the safest habit.
- Make the even numbers from 2 to 20.
- Make the first day of every month of 2026 (12 rows), using
date(d, '+1 month'). - List Golf's bosses, from Golf up to the top, with the level of each.
Show the answer
WITH RECURSIVE even(n) AS (
SELECT 2
UNION ALL
SELECT n + 2 FROM even WHERE n < 20
)
SELECT n FROM even;
WITH RECURSIVE month(d) AS (
SELECT '2026-01-01'
UNION ALL
SELECT date(d, '+1 month') FROM month WHERE d < '2026-12-01'
)
SELECT d FROM month;
WITH RECURSIVE up(id, name, boss_id, level) AS (
SELECT id, name, boss_id, 0 FROM staff WHERE name = 'Golf'
UNION ALL
SELECT s.id, s.name, s.boss_id, u.level + 1
FROM staff AS s JOIN up AS u ON s.id = u.boss_id
)
SELECT level, name FROM up ORDER BY level;| n |
|---|
| 2 |
| 4 |
| 6 |
| 8 |
| 10 |
| 12 |
| 14 |
| 16 |
| 18 |
| 20 |
| d |
|---|
| 2026-01-01 |
| 2026-02-01 |
| 2026-03-01 |
| 2026-04-01 |
| 2026-05-01 |
| 2026-06-01 |
| 2026-07-01 |
| 2026-08-01 |
| 2026-09-01 |
| 2026-10-01 |
| 2026-11-01 |
| 2026-12-01 |
| level | name |
|---|---|
| 0 | Golf |
| 1 | Ton |
| 2 | Pranee |
Phai (bamboo), given as a gift of knowledge: free to use, learn from and pass on · every example on this page was run on Phai SQL and checked against SQLite when the page was made