Subqueries and CTEs · Lesson 55 of 64

SQL Recursive CTEs

What you will learn

  • The two parts of a recursive CTE
  • How to generate numbers and dates
  • How to walk a tree (managers, categories)
  • How to make it stop

This lesson runs on the sample database you chose in lesson 1.1 (use the Example data picker at the top). Run the cells from top to bottom.

1. A query that uses itself

A recursive CTE has two parts joined by UNION ALL:

  1. the start (the anchor): rows that begin the result;
  2. the step (the recursive part): a query that reads the CTE's own previous rows and produces new ones.

The database repeats the step until it produces no new rows:

WITH RECURSIVE count_up(n) AS (
    SELECT 1                       -- start
    UNION ALL
    SELECT n + 1 FROM count_up     -- step
    WHERE n < 5                    -- stop
)
SELECT n FROM count_up;
n
-
1
2
3
4
5
(5 rows)
WITH RECURSIVE count_up(n) AS (
    SELECT 1                       -- start
    UNION ALL
    SELECT n + 1 FROM count_up     -- step
    WHERE n < 5                    -- stop
)
SELECT n FROM count_up;
n
-
1
2
3
4
5
(5 rows)
WITH RECURSIVE count_up(n) AS (
    SELECT 1                       -- start
    UNION ALL
    SELECT n + 1 FROM count_up     -- step
    WHERE n < 5                    -- stop
)
SELECT n FROM count_up;
n
-
1
2
3
4
5
(5 rows)

Start with 1; the step adds 1 to the last row; the WHERE stops it at 5. Without a stopping condition the query never ends.

2. Generate a calendar

Recursion can build a list of dates (an ISO date plus one day, lesson 1.7). Joined to your data, it shows days with no rows:

WITH RECURSIVE days(d) AS (
    SELECT '2026-03-01'
    UNION ALL
    SELECT DATE(d, '+1 day') FROM days WHERE d < '2026-03-07'
)
SELECT d, STRFTIME('%w', d) AS weekday_number FROM days;
d           weekday_number
----------  --------------
2026-03-01  0
2026-03-02  1
2026-03-03  2
2026-03-04  3
2026-03-05  4
2026-03-06  5
2026-03-07  6
(7 rows)
WITH RECURSIVE days(d) AS (
    SELECT '2026-03-01'
    UNION ALL
    SELECT DATE(d, '+1 day') FROM days WHERE d < '2026-03-07'
)
SELECT d, STRFTIME('%w', d) AS weekday_number FROM days;
d           weekday_number
----------  --------------
2026-03-01  0
2026-03-02  1
2026-03-03  2
2026-03-04  3
2026-03-05  4
2026-03-06  5
2026-03-07  6
(7 rows)
WITH RECURSIVE days(d) AS (
    SELECT '2026-03-01'
    UNION ALL
    SELECT DATE(d, '+1 day') FROM days WHERE d < '2026-03-07'
)
SELECT d, STRFTIME('%w', d) AS weekday_number FROM days;
d           weekday_number
----------  --------------
2026-03-01  0
2026-03-02  1
2026-03-03  2
2026-03-04  3
2026-03-05  4
2026-03-06  5
2026-03-07  6
(7 rows)

Orders per day for the first week of the Shop's data, including days with none:

WITH RECURSIVE days(d) AS (
    SELECT MIN(order_date) FROM orders
    UNION ALL
    SELECT DATE(d, '+1 day') FROM days WHERE d < DATE((SELECT MIN(order_date) FROM orders), '+6 day')
)
SELECT days.d AS day, COUNT(o.order_id) AS orders
FROM days LEFT JOIN orders AS o ON o.order_date = days.d
GROUP BY days.d ORDER BY days.d;
day         orders
----------  ------
2024-01-01       1
2024-01-02       0
2024-01-03       2
2024-01-04       0
2024-01-05       1
2024-01-06       0
2024-01-07       0
(7 rows)

Transactions per day for the first week of the Bank's data, including days with none:

WITH RECURSIVE days(d) AS (
    SELECT MIN(txn_date) FROM transactions
    UNION ALL
    SELECT DATE(d, '+1 day') FROM days WHERE d < DATE((SELECT MIN(txn_date) FROM transactions), '+6 day')
)
SELECT days.d AS day, COUNT(t.txn_id) AS transactions
FROM days LEFT JOIN transactions AS t ON t.txn_date = days.d
GROUP BY days.d ORDER BY days.d;
day         transactions
----------  ------------
2018-02-23             2
2018-02-24             0
2018-02-25             0
2018-02-26             0
2018-02-27             0
2018-02-28             0
2018-03-01             0
(7 rows)

Class days with attendance records, for the first week of the School's data, including days with none:

WITH RECURSIVE days(d) AS (
    SELECT MIN(class_date) FROM attendance
    UNION ALL
    SELECT DATE(d, '+1 day') FROM days WHERE d < DATE((SELECT MIN(class_date) FROM attendance), '+6 day')
)
SELECT days.d AS day, COUNT(a.student_id) AS records
FROM days LEFT JOIN attendance AS a ON a.class_date = days.d
GROUP BY days.d ORDER BY days.d;
day         records
----------  -------
2025-02-03       79
2025-02-04       50
2025-02-05       42
2025-02-06       66
2025-02-07      162
2025-02-08        0
2025-02-09        0
(7 rows)

A GROUP BY on the data alone would skip the empty days; the generated calendar plus a LEFT JOIN shows them as 0.

3. Walk a tree

Some tables point to themselves: a row holds the id of its parent (lesson 4.6). Recursion follows the links, level by level:

The reporting chain of the Shop's employees, from the top manager down:

WITH RECURSIVE chain(employee_id, name, manager_id, level) AS (
    SELECT employee_id, name, manager_id, 0 FROM employees WHERE manager_id IS NULL
    UNION ALL
    SELECT e.employee_id, e.name, e.manager_id, c.level + 1
    FROM employees AS e JOIN chain AS c ON e.manager_id = c.employee_id
)
SELECT level, COUNT(*) AS people FROM chain GROUP BY level ORDER BY level;
level  people
-----  ------
    0       1
    1       4
    2       9
(3 rows)

The Bank has no table that points to itself, so build a small tree of your own:

CREATE TABLE lib_units (unit_id INTEGER PRIMARY KEY, name TEXT, parent_id INTEGER);
INSERT INTO lib_units VALUES (1, 'Head office', NULL), (2, 'Retail', 1), (3, 'Corporate', 1), (4, 'Branches', 2), (5, 'Online', 2);
WITH RECURSIVE tree(unit_id, name, level) AS (
    SELECT unit_id, name, 0 FROM lib_units WHERE parent_id IS NULL
    UNION ALL
    SELECT u.unit_id, u.name, t.level + 1 FROM lib_units AS u JOIN tree AS t ON u.parent_id = t.unit_id
)
SELECT level, COUNT(*) AS units FROM tree GROUP BY level ORDER BY level;
level  units
-----  -----
    0      1
    1      2
    2      2
(3 rows)

The School has no table that points to itself, so build a small tree of your own:

CREATE TABLE lib_units (unit_id INTEGER PRIMARY KEY, name TEXT, parent_id INTEGER);
INSERT INTO lib_units VALUES (1, 'School', NULL), (2, 'Primary', 1), (3, 'Secondary', 1), (4, 'Year 1', 2), (5, 'Year 2', 2);
WITH RECURSIVE tree(unit_id, name, level) AS (
    SELECT unit_id, name, 0 FROM lib_units WHERE parent_id IS NULL
    UNION ALL
    SELECT u.unit_id, u.name, t.level + 1 FROM lib_units AS u JOIN tree AS t ON u.parent_id = t.unit_id
)
SELECT level, COUNT(*) AS units FROM tree GROUP BY level ORDER BY level;
level  units
-----  -----
    0      1
    1      2
    2      2
(3 rows)

The start finds the top (no parent). The step finds the children of rows already found. The level column counts how deep each row is.

4. Show the path

Carry text along in the recursion to build a path such as Head > Retail > Online:

CREATE TABLE lib_nodes (node_id INTEGER PRIMARY KEY, name TEXT, parent_id INTEGER);
INSERT INTO lib_nodes VALUES (1, 'Head', NULL), (2, 'Retail', 1), (3, 'Online', 2), (4, 'Corporate', 1);
WITH RECURSIVE paths(node_id, path) AS (
    SELECT node_id, name FROM lib_nodes WHERE parent_id IS NULL
    UNION ALL
    SELECT n.node_id, p.path || ' > ' || n.name FROM lib_nodes AS n JOIN paths AS p ON n.parent_id = p.node_id
)
SELECT path FROM paths ORDER BY path;
path
----------------------
Head
Head > Corporate
Head > Retail
Head > Retail > Online
(4 rows)
CREATE TABLE lib_nodes (node_id INTEGER PRIMARY KEY, name TEXT, parent_id INTEGER);
INSERT INTO lib_nodes VALUES (1, 'Head', NULL), (2, 'Retail', 1), (3, 'Online', 2), (4, 'Corporate', 1);
WITH RECURSIVE paths(node_id, path) AS (
    SELECT node_id, name FROM lib_nodes WHERE parent_id IS NULL
    UNION ALL
    SELECT n.node_id, p.path || ' > ' || n.name FROM lib_nodes AS n JOIN paths AS p ON n.parent_id = p.node_id
)
SELECT path FROM paths ORDER BY path;
path
----------------------
Head
Head > Corporate
Head > Retail
Head > Retail > Online
(4 rows)
CREATE TABLE lib_nodes (node_id INTEGER PRIMARY KEY, name TEXT, parent_id INTEGER);
INSERT INTO lib_nodes VALUES (1, 'Head', NULL), (2, 'Retail', 1), (3, 'Online', 2), (4, 'Corporate', 1);
WITH RECURSIVE paths(node_id, path) AS (
    SELECT node_id, name FROM lib_nodes WHERE parent_id IS NULL
    UNION ALL
    SELECT n.node_id, p.path || ' > ' || n.name FROM lib_nodes AS n JOIN paths AS p ON n.parent_id = p.node_id
)
SELECT path FROM paths ORDER BY path;
path
----------------------
Head
Head > Corporate
Head > Retail
Head > Retail > Online
(4 rows)

5. Making it stop

  • A stop condition in the step (WHERE n < 5) or the data running out (no more children).
  • If the data has a loop (A is the parent of B and B of A) the recursion never ends. A level < 20 guard in the step is a cheap safety net.
  • UNION (instead of UNION ALL) drops repeated rows and can also stop a loop, but costs more.

Worked example: how deep is the tree?

Part Query
start rows with no parent, level = 0
step children of found rows, level + 1, and WHERE level < 20
final SELECT MAX(level) FROM tree

The answer is the depth of the tree. The guard stops the query even if the data has a loop by mistake. The table is made up.

Common mistakes

  • No stop condition.
  • A loop in the data with no guard.
  • UNION ALL between unrelated queries instead of anchor and step.
  • Forgetting that the step must read the CTE itself.
  • Using recursion for what a simple GROUP BY can do.

Key takeaways

  • A recursive CTE has a start, UNION ALL, and a step that reads the CTE itself.
  • It can generate numbers and dates, and walk trees by following parent links.
  • Always give it a way to stop; a level guard protects against loops in the data.
  • Carry level or path columns along to describe each row.

Practice

1. What are the two parts of a recursive CTE?

Show answer

The start (anchor) and the step (the recursive part), joined by UNION ALL.

2. What happens without a stop condition?

Show answer

The query keeps producing rows and never ends.

3. How do you find the top of a tree in the start part?

Show answer

Select the rows whose parent column is NULL.

4. Why generate a calendar for a report?

Show answer

A LEFT JOIN from the calendar shows days that have no rows as 0, which a plain GROUP BY would skip.

5. How do you protect against a loop in the data?

Show answer

Add a depth guard such as WHERE level < 20 in the step.

6. How do you build a path like A > B > C?

Show answer

Carry a text column along and add || ' > ' || name in each step.