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
10 rows

A recursive CTE always has two parts joined by UNION ALL:

How it runs, step by step

The database keeps a queue of rows waiting to be used:

  1. Run the start. It gives 1: put it in the result and in the queue.
  2. Take the first row out of the queue (x = 1) and run the step with n holding just that row. It gives 2: into the result and the queue.
  3. Take 2 out, run the step: it gives 3. And so on.
  4. At x = 10 the step's WHERE x < 10 is false, so it gives nothing. Nothing new goes into the queue.
  5. The queue is empty: the CTE is finished, with the 10 rows it made.
Row takenThe step givesQueue after
(start)11
122
233
.........
91010
10nothing (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;
xtotal
11
23
36
410
515
621
728
836
945
1055
10 rows

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;
dorders
2026-11-010
2026-11-021
2026-11-030
2026-11-040
2026-11-051
2026-11-060
2026-11-070
2026-11-080
2026-11-090
2026-11-100
10 rows

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);
✓ 7 rows changed

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;
depthnamepath
0PraneePranee
1DaoPranee > Dao
2BeamPranee > Dao > Beam
3MewPranee > Dao > Beam > Mew
2NokPranee > Dao > Nok
1TonPranee > Ton
2GolfPranee > Ton > Golf
7 rows

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;
namerole
Daoshop manager
Nokcashier
Beambarista
Mewtrainee barista
4 rows

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;
levelname
0Mew
1Beam
2Dao
3Pranee
4 rows

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:

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
5 rows

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;
levelname
0Mew
1Beam
2Dao
3Pranee
4Mew
5Beam
6Dao
7 rows

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;
✓ 1 row changed

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
5 rows

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.

  1. Make the even numbers from 2 to 20.
  2. Make the first day of every month of 2026 (12 rows), using date(d, '+1 month').
  3. 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
10 rows
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
12 rows
levelname
0Golf
1Ton
2Pranee
3 rows

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