Recursive queries: trees and missing dates
WITH RECURSIVE t AS (starting point UNION ALL SELECT … FROM t WHERE stop condition): the starting point runs first, then each round works from the rows of the round before, and it stops when no new rows come out. After generating the months, LEFT JOIN the data and fill the gaps with COALESCE(…, 0). To walk a tree, use JOIN t ON child.parent_id = t.id.
In lesson 2 you found that February had no orders, so grouping by month simply dropped that row. Because of that, the moving average in lesson 5 and the month-over-month change in lesson 6 both came out wrong. Back then the advice was "fill in the missing months first", and this lesson does exactly that. The tool is WITH RECURSIVE: a WITH that calls itself.
Counting from 1 to 5
In this step you first see how recursion runs. With no table at all, generate 1 to 5:
1WITH RECURSIVE nums AS (2 SELECT 1 AS n3 UNION ALL4 SELECT n + 15 FROM nums6 WHERE n < 57)8SELECT n9FROM nums;
| n |
|---|
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
It has two halves, joined by UNION ALL:
- The starting point:
SELECT 1 AS nruns only once and gives the first row, 1. - The recursive half:
SELECT n + 1 FROM nums WHERE n < 5. HereFROM numsmeans the rows from the round before. Round one gets 1 and works out 2; round two gets 2 and works out 3, and so on. When it gets 5,n < 5is false, no row comes out, and it stops.
| n |
|---|
| 1 |
SELECT n + 1 FROM nums WHERE n < 5| n |
|---|
| 1 |
| 2 |
one more round| n |
|---|
| 1 |
| 2 |
| 3 |
… until n = 5| n |
|---|
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
What happens if you forget the stop condition WHERE n < 5?
1WITH RECURSIVE nums AS (2 SELECT 1 AS n3 UNION ALL4 SELECT n + 15 FROM nums6)7SELECT n8FROM nums;
cte_max_recursion_depth), and past that it gives ERROR 3636. When you write a recursive query, first decide where it stops.Generating 12 months
In this step you swap the numbers for dates. Start from January 1 and add one month each round, up to December:
1WITH RECURSIVE months AS (2 SELECT DATE('2025-01-01') AS month_start3 UNION ALL4 SELECT DATE_ADD(month_start, INTERVAL 1 MONTH)5 FROM months6 WHERE month_start < '2025-12-01'7)8SELECT month_start9FROM months;
| month_start |
|---|
| 2025-01-01 |
| 2025-02-01 |
| 2025-03-01 |
| 2025-04-01 |
| 2025-05-01 |
| 2025-06-01 |
| 2025-07-01 |
| 2025-08-01 |
| 2025-09-01 |
| 2025-10-01 |
| 2025-11-01 |
| 2025-12-01 |
12 rows, not a single month missing, and February is there too. This "calendar table" doesn't depend on any data: it's there whether there are orders or not.
To generate the 7 days from December 1 to December 7, how many days do you add each round?
1WITH RECURSIVE days AS (2 SELECT DATE('2025-12-01') AS day3 UNION ALL4 SELECT DATE_ADD(day, INTERVAL DAY)5 FROM days6 WHERE day < '2025-12-07'7)8SELECT day FROM days;
day < '2025-12-07' is false, and it stops.Filling in the months with no orders
In this step you join the calendar table with the orders. Put the calendar on the left and LEFT JOIN each month's sales: every month in the calendar stays, the side with no match is NULL, and COALESCE turns that into 0:
1WITH RECURSIVE months AS (2 SELECT DATE('2025-01-01') AS month_start3 UNION ALL4 SELECT DATE_ADD(month_start, INTERVAL 1 MONTH)5 FROM months6 WHERE month_start < '2025-12-01'7),8sales AS (9 SELECT DATE_SUB(order_date, INTERVAL DAY(order_date) - 1 DAY) AS month_start,10 SUM(amount) AS sales11 FROM orders12 WHERE status = 'paid'13 GROUP BY month_start14)15SELECT DATE_FORMAT(m.month_start, '%Y-%m') AS month,16 COALESCE(s.sales, 0) AS sales17FROM months AS m18LEFT JOIN sales AS s ON s.month_start = m.month_start19ORDER BY m.month_start;
| month | sales |
|---|---|
| 2025-01 | 36 |
| 2025-02 | 0 |
| 2025-03 | 366 |
| 2025-04 | 126 |
| 2025-05 | 743 |
| 2025-06 | 310 |
| 2025-07 | 820 |
| 2025-08 | 626 |
| 2025-09 | 977 |
| 2025-10 | 789 |
| 2025-11 | 1042 |
| 2025-12 | 588 |
February finally shows up, with sales of 0. Now if you work out moving averages or month-over-month change on top of this, "the previous row" is always "last month".
| month_start |
|---|
| 2025-01-01 |
| 2025-02-01 |
| 2025-03-01 |
LEFT JOIN sales … COALESCE(s.sales, 0)| month | sales |
|---|---|
| 2025-01 | 36 |
| 2025-02 | 0 |
| 2025-03 | 366 |
Orders per day, with no day missing
✓From December 1 to 10, how many paid orders were there each day? Days with no orders should show 0. Two columns: day and orders, sorted by date.
| day | orders |
|---|---|
| 2025-12-01 | 0 |
| 2025-12-02 | 0 |
| 2025-12-03 | 0 |
| 2025-12-04 | 1 |
| 2025-12-05 | 0 |
| 2025-12-06 | 1 |
| 2025-12-07 | 0 |
| 2025-12-08 | 1 |
| 2025-12-09 | 1 |
| 2025-12-10 | 1 |
1WITH RECURSIVE days AS (2 SELECT DATE('2025-12-01') AS day3 UNION ALL4 SELECT DATE_ADD(day, INTERVAL 1 DAY)5 FROM days6 WHERE day < '2025-12-10'7),8daily AS (9 SELECT order_date, COUNT(*) AS n10 FROM orders11 WHERE status = 'paid'12 GROUP BY order_date13)14SELECT d.day15FROM days AS d16ORDER BY d.day;
Walking a tree
In this step you use recursion on a different kind of data: a tree. The shop plans to split its product categories into finer ones: under "all" there are 4 main categories, under tech there are audio and power, and under audio there are speakers. Each category records the level above it in parent_id:
1CREATE TABLE categories (id INT PRIMARY KEY, name VARCHAR(20), parent_id INT);2INSERT INTO categories VALUES (1, 'all', NULL), (2, 'office', 1), (3, 'tech', 1),3 (4, 'home', 1), (5, 'food', 1), (6, 'audio', 3), (7, 'power', 3),4 (8, 'drinks', 5), (9, 'speakers', 6);5WITH RECURSIVE tree AS (6 SELECT id, name, 1 AS level, CAST(name AS CHAR(100)) AS path7 FROM categories8 WHERE parent_id IS NULL9 UNION ALL10 SELECT c.id, c.name, t.level + 1, CONCAT(t.path, ' > ', c.name)11 FROM categories AS c12 JOIN tree AS t ON c.parent_id = t.id13)14SELECT id, name, level, path15FROM tree16ORDER BY path;
| id | name | level | path |
|---|---|---|---|
| 1 | all | 1 | all |
| 5 | food | 2 | all > food |
| 8 | drinks | 3 | all > food > drinks |
| 4 | home | 2 | all > home |
| 2 | office | 2 | all > office |
| 3 | tech | 2 | all > tech |
| 6 | audio | 3 | all > tech > audio |
| 9 | speakers | 4 | all > tech > audio > speakers |
| 7 | power | 3 | all > tech > power |
The starting point is the root, all, which has no level above it. Each round finds the categories whose parent_id equals an id from the round before, adds 1 to the level, and adds its own name to the path. It takes as many rounds as the tree has levels. At the leaves there are no new rows to find, so it stops by itself.
The CAST(name AS CHAR(100)) in the starting point leaves enough room for path: how wide a recursive column is gets decided by the starting point, and without the extra room, longer paths wouldn't fit.
What level is speakers on?
level.Everything below and everything above
In this step you write the two most common tree queries. Everything below: start from a given category and walk down. For example, "sales for tech" has to include audio, power and speakers, so first you find every category under tech:
Every category under tech
✓Find tech itself and every category on every level below it. Two columns: id and name, sorted by id.
| id | name |
|---|---|
| 3 | tech |
| 6 | audio |
| 7 | power |
| 9 | speakers |
1CREATE TABLE categories (id INT PRIMARY KEY, name VARCHAR(20), parent_id INT);2INSERT INTO categories VALUES (1, 'all', NULL), (2, 'office', 1), (3, 'tech', 1),3 (4, 'home', 1), (5, 'food', 1), (6, 'audio', 3), (7, 'power', 3),4 (8, 'drinks', 5), (9, 'speakers', 6);5WITH RECURSIVE sub AS (6 SELECT id, name7 FROM categories8 WHERE name = 'tech'9)10SELECT id, name11FROM sub12ORDER BY id;
Everything above goes the other way: start from speakers, and each round find the row whose id equals my parent_id, all the way up to the root. The join condition just turns around: JOIN up ON c.id = up.parent_id. "All my managers" in an org chart, or "which post this reply belongs to" in a comment thread, are written the same way.
Put these lines in order to make a query that runs: walk from speakers all the way up to the root, with the step number.
WITH RECURSIVE up AS (SELECT c.id, c.name, c.parent_id, up.step + 1 FROM categories AS c JOIN up ON c.id = up.parent_idSELECT step, name FROM up ORDER BY step;UNION ALL)INSERT INTO categories VALUES (1, 'all', NULL), (3, 'tech', 1), (6, 'audio', 3), (9, 'speakers', 6);SELECT id, name, parent_id, 0 AS step FROM categories WHERE name = 'speakers'CREATE TABLE categories (id INT PRIMARY KEY, name VARCHAR(20), parent_id INT);
step | name 0 | speakers 1 | audio 2 | tech 3 | all
UNION ALL, and last the half that walks up. When it reaches all, its parent_id is NULL, so there's no level above to find, and it stops.What you learned
WITH RECURSIVE: the starting point,UNION ALL, then the recursive half. In the recursive half,FROM itselfmeans the new rows of the round before, and it stops when no new rows come out.- Always have a stop condition, or you get
ERROR 3636at 1000 rounds. - To generate a run of months or days: start from the first day and
DATE_ADDone month or one day each round. - Filling gaps: put the calendar on the left,
LEFT JOINthe data, and useCOALESCE(…, 0). Fill the gaps before working out moving averages or month-over-month change over time. - Walking a tree: start from the root (
parent_id IS NULL) and walk down withJOIN t ON child.parent_id = t.id.level + 1keeps the level,CONCATbuilds the path, and aCASTin the starting point leaves enough room. - Walking up:
JOIN t ON c.id = t.parent_id.