Kodewick
Start learning →
Recursive queries: trees and missing dates10 / 12

Recursive queries: trees and missing dates

Lesson 10 of 12 · Part 4 · Reports · about 20 minutes

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:

main.sql
1WITH RECURSIVE nums AS (2    SELECT 1 AS n3    UNION ALL4    SELECT n + 15    FROM nums6    WHERE n < 57)8SELECT n9FROM nums;
Output
n
1
2
3
4
5
5 rows

It has two halves, joined by UNION ALL:

  • The starting point: SELECT 1 AS n runs only once and gives the first row, 1.
  • The recursive half: SELECT n + 1 FROM nums WHERE n < 5. Here FROM nums means 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 < 5 is false, no row comes out, and it stops.
start
n
1
SELECT n + 1 FROM nums WHERE n < 5
round 1
n
1
2
one more round
round 2
n
1
2
3
… until n = 5
result
n
1
2
3
4
5
Each round works only from the new rows of the round before, and it stops when no new rows come out
Choose oneA wrong guess is fine

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;

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:

main.sql
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;
Output
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

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.

Fill inTap one to fill a blank; tap a blank to take it back

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;

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:

main.sql
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;
Output
monthsales
2025-0136
2025-020
2025-03366
2025-04126
2025-05743
2025-06310
2025-07820
2025-08626
2025-09977
2025-10789
2025-111042
2025-12588
12 rows

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".

months
month_start
2025-01-01
2025-02-01
2025-03-01
LEFT JOIN sales … COALESCE(s.sales, 0)
result
monthsales
2025-0136
2025-020
2025-03366
The calendar is on the left, so every month stays; months with no orders become 0
Exercise 1

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.

It should print
dayorders
2025-12-010
2025-12-020
2025-12-030
2025-12-041
2025-12-050
2025-12-061
2025-12-070
2025-12-081
2025-12-091
2025-12-101
10 rows
exercise1.sql
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;
Output
Press Run or Ctrl+Enter

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:

main.sql
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;
Output
Statement on line 1
Query OK, 0 rows affected
Statement on line 2
Query OK, 9 rows affected · Records: 9 Duplicates: 0 Warnings: 0
Statement on line 5
idnamelevelpath
1all1all
5food2all > food
8drinks3all > food > drinks
4home2all > home
2office2all > office
3tech2all > tech
6audio3all > tech > audio
9speakers4all > tech > audio > speakers
7power3all > tech > power
9 rows

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.

Choose one

What level is speakers on?

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:

Exercise 2

Every category under tech

Find tech itself and every category on every level below it. Two columns: id and name, sorted by id.

It should print
idname
3tech
6audio
7power
9speakers
4 rows
exercise2.sql
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;
Output
Press Run or Ctrl+Enter

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 in orderDrag, or use the arrows

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.

  1. WITH RECURSIVE up AS (
  2. SELECT c.id, c.name, c.parent_id, up.step + 1 FROM categories AS c JOIN up ON c.id = up.parent_id
  3. SELECT step, name FROM up ORDER BY step;
  4. UNION ALL
  5. )
  6. INSERT INTO categories VALUES (1, 'all', NULL), (3, 'tech', 1), (6, 'audio', 3), (9, 'speakers', 6);
  7. SELECT id, name, parent_id, 0 AS step FROM categories WHERE name = 'speakers'
  8. CREATE TABLE categories (id INT PRIMARY KEY, name VARCHAR(20), parent_id INT);
Should print
step | name
0 | speakers
1 | audio
2 | tech
3 | all

What you learned

  • WITH RECURSIVE: the starting point, UNION ALL, then the recursive half. In the recursive half, FROM itself means 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 3636 at 1000 rounds.
  • To generate a run of months or days: start from the first day and DATE_ADD one month or one day each round.
  • Filling gaps: put the calendar on the left, LEFT JOIN the data, and use COALESCE(…, 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 with JOIN t ON child.parent_id = t.id. level + 1 keeps the level, CONCAT builds the path, and a CAST in the starting point leaves enough room.
  • Walking up: JOIN t ON c.id = t.parent_id.