SQL recursive CTE: walk a hierarchy or build a series in one query
Who reports to whom, and how many levels down? Which days in June had no sales at all? A normal query struggles with both, because you don't know how deep the hierarchy goes, and the missing days aren't stored in any table. A recursive CTE builds its result itself, one round at a time.
In short: WITH RECURSIVE name AS (anchor UNION ALL recursive part) SELECT … FROM name. The anchor returns the starting rows. The recursive part reads name itself and produces new rows from it, round after round. As soon as a round returns nothing, the query is done. The stopping condition, usually a WHERE or a join, makes sure that moment comes.
Before you start: CTEs with WITH, the employees table from the self join lesson, and LEFT JOIN.
Try it now
Each row in employees stores the employee_id of that person's manager in manager_id. A self join gets you exactly one level. A recursive CTE keeps going until nobody is left underneath.
Task HR is putting together an org chart. Show first_name, last_name and level for every employee: the head of the company (no manager_id) is level 1, their direct reports are level 2, and so on. The query should still work when the org chart gets deeper.
employees 10 rows, 7 columns
| employee_id | first_name | last_name | department | salary | hire_date | manager_id |
|---|---|---|---|---|---|---|
| 1 | Karen | Mitchell | Management | 93600 | 2018-01-02 | NULL |
| 2 | Tom | Bradley | Sales | 62400 | 2019-04-01 | 1 |
| 3 | Julia | Reyes | Sales | 46800 | 2021-06-15 | 2 |
| 4 | Marcus | Allen | Sales | 49200 | 2020-09-01 | 2 |
| 5 | Sarah | Long | Warehouse | 39600 | 2022-02-01 | 1 |
| 6 | Felix | Turner | Warehouse | 35400 | 2024-03-18 | 5 |
| 7 | Nina | Cooper | Accounting | 52800 | 2019-10-01 | 1 |
| 8 | David | Ross | Customer service | 38400 | 2023-05-02 | 2 |
| 9 | Laura | Hughes | Customer service | NULL | 2025-09-01 | 2 |
| 10 | Paul | Ward | Accounting | 43200 | 2022-11-14 | 7 |
How WITH RECURSIVE works
The smallest possible example counts from 1 to 5:
WITH RECURSIVE numbers(n) AS (
SELECT 1 -- anchor
UNION ALL
SELECT n + 1 FROM numbers -- recursive part
WHERE n < 5 -- stopping condition
)
SELECT n FROM numbers;
| n |
|---|
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
Behind the scenes there is a queue. The anchor puts 1 into it. The database then takes one row out, adds it to the result and runs the recursive part with just that row: 1 becomes 2, which goes into the queue. At n = 5, WHERE n < 5 lets nothing through, the queue runs dry and the query ends. Without that condition it would count forever.
Climbing a hierarchy
The same idea works on real tables. Instead of n + 1, the recursive part uses a join to fetch the next person. Who sits above Felix Turner (employee_id 6), all the way to the top?
WITH RECURSIVE bosses AS (
SELECT employee_id, first_name, last_name, manager_id, 1 AS step
FROM employees
WHERE employee_id = 6
UNION ALL
SELECT e.employee_id, e.first_name, e.last_name, e.manager_id, b.step + 1
FROM employees e
JOIN bosses b ON e.employee_id = b.manager_id
)
SELECT step, first_name, last_name FROM bosses;
| step | first_name | last_name |
|---|---|---|
| 1 | Felix | Turner |
| 2 | Sarah | Long |
| 3 | Karen | Mitchell |
Here the join is the stopping condition: Karen Mitchell has no manager_id, so the next round finds nobody. The direction depends only on the ON condition. e.employee_id = b.manager_id climbs up to the boss; e.manager_id = b.employee_id walks down to everyone who reports to the person just found. In the first exercise you walked down.
One more exercise: finding gaps in daily sales
A GROUP BY on orders only shows days on which something was ordered. A daily report, though, needs every day, including the ones at zero. You generate the days with a recursive CTE, just like the numbers above but with date(day, '+1 day') instead of n + 1, and then attach the orders with a LEFT JOIN.
Task Management wants daily revenue from 1 June to 15 June 2026, for every single day, including days without orders (show 0 there). Show day and revenue (the sum of quantity * unit_price, cancelled orders don't count), sorted by day. Generate the days with WITH RECURSIVE.
orders 18 rows, 5 columns
| order_id | customer_id | order_date | status | employee_id |
|---|---|---|---|---|
| 1001 | 1 | 2026-01-08 | delivered | 3 |
| 1002 | 4 | 2026-01-12 | delivered | 4 |
| 1003 | 3 | 2026-01-20 | delivered | 3 |
| 1004 | 7 | 2026-02-03 | delivered | 4 |
| 1005 | 2 | 2026-02-11 | cancelled | 8 |
| 1006 | 1 | 2026-02-25 | delivered | 3 |
| 1007 | 10 | 2026-03-04 | delivered | 2 |
| 1008 | 5 | 2026-03-17 | delivered | 4 |
| 1009 | 8 | 2026-03-30 | delivered | 3 |
| 1010 | 6 | 2026-04-07 | delivered | 8 |
| 1011 | 12 | 2026-04-22 | delivered | 4 |
| 1012 | 3 | 2026-05-06 | delivered | 3 |
| 1013 | 9 | 2026-05-19 | cancelled | 8 |
| 1014 | 7 | 2026-06-02 | shipped | 4 |
| 1015 | 1 | 2026-06-10 | shipped | 3 |
| 1016 | 11 | 2026-06-12 | open | NULL |
| 1017 | 4 | 2026-06-13 | open | NULL |
| 1018 | 10 | 2026-06-14 | open | NULL |
order_items 38 rows, 4 columns
| order_id | product_id | quantity | unit_price |
|---|---|---|---|
| 1001 | 1 | 40 | 4.79 |
| 1001 | 3 | 25 | 2.79 |
| 1001 | 6 | 4 | 24.9 |
| 1002 | 2 | 2 | 3.49 |
| 1002 | 10 | 3 | 5.49 |
| 1003 | 1 | 60 | 4.69 |
| 1003 | 11 | 6 | 84.9 |
| 1003 | 3 | 50 | 2.59 |
| 1004 | 4 | 3 | 179 |
| 1004 | 9 | 3 | 269 |
| 1005 | 5 | 1 | 449 |
| 1006 | 1 | 30 | 4.79 |
| 1006 | 7 | 10 | 6.99 |
| 1007 | 8 | 2 | 219 |
| 1007 | 11 | 4 | 89.9 |
| 1007 | 1 | 20 | 4.99 |
| 1008 | 4 | 6 | 175 |
| 1008 | 2 | 5 | 3.49 |
| 1009 | 10 | 120 | 4.99 |
| 1009 | 2 | 40 | 3.19 |
| 1009 | 9 | 2 | 279 |
| 1010 | 7 | 2 | 6.99 |
| 1010 | 2 | 1 | 3.49 |
| 1011 | 12 | 1 | 129 |
| 1011 | 1 | 10 | 4.99 |
| 1011 | 3 | 12 | 2.79 |
| 1012 | 6 | 8 | 23.9 |
| 1012 | 1 | 40 | 4.69 |
| 1013 | 9 | 1 | 279 |
| 1014 | 5 | 2 | 439 |
| 1014 | 4 | 2 | 179 |
| 1015 | 1 | 50 | 4.79 |
| 1015 | 11 | 2 | 89.9 |
| 1016 | 10 | 4 | 5.49 |
| 1017 | 2 | 3 | 3.49 |
| 1017 | 7 | 2 | 6.99 |
| 1018 | 1 | 80 | 4.79 |
| 1018 | 6 | 10 | 24.9 |
This exercise is part of Premium.
Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.
See Premium Already Premium? Log in
The first exercise in this lesson is free.
One more exercise: the reporting line as text
Any column can keep growing from round to round, text included. That gives you a path, much like a folder path on your computer.
Task The intranet should show each employee's reporting line. Show employee_id and path: the last names from the head of the company down to the person, separated by ' / ', so for Julia Reyes 'Mitchell / Bradley / Reyes'. The head of the company just gets her own last name.
employees 10 rows, 7 columns
| employee_id | first_name | last_name | department | salary | hire_date | manager_id |
|---|---|---|---|---|---|---|
| 1 | Karen | Mitchell | Management | 93600 | 2018-01-02 | NULL |
| 2 | Tom | Bradley | Sales | 62400 | 2019-04-01 | 1 |
| 3 | Julia | Reyes | Sales | 46800 | 2021-06-15 | 2 |
| 4 | Marcus | Allen | Sales | 49200 | 2020-09-01 | 2 |
| 5 | Sarah | Long | Warehouse | 39600 | 2022-02-01 | 1 |
| 6 | Felix | Turner | Warehouse | 35400 | 2024-03-18 | 5 |
| 7 | Nina | Cooper | Accounting | 52800 | 2019-10-01 | 1 |
| 8 | David | Ross | Customer service | 38400 | 2023-05-02 | 2 |
| 9 | Laura | Hughes | Customer service | NULL | 2025-09-01 | 2 |
| 10 | Paul | Ward | Accounting | 43200 | 2022-11-14 | 7 |
This exercise is part of Premium.
Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.
See Premium Already Premium? Log in
The first exercise in this lesson is free.
Avoiding infinite loops
A recursive query only stops when a round eventually returns no rows. Three things help:
- Stop condition in the recursive part: the WHERE belongs in the part after UNION ALL, not in the outer query. A
WHERE n <= 5at the very bottom only filters the output; the recursion itself never ends. - LIMIT as a safety net: in SQLite, a LIMIT in the recursive part always stops the recursion, for example
SELECT n + 1 FROM numbers LIMIT 1000. The SQLite docs recommend it whenever you know an upper bound. - Cycles in the data: if a typo makes A the manager of B and B the manager of A, a join goes round in circles. UNION instead of UNION ALL drops rows that were seen before, but that stops helping once a column like level changes every round.
Common mistakes
No stopping condition
Without a WHERE in the recursive part, the CTE grows without end. If the outer query just reads it, the exercise stops reading after 5000 rows and you see the start of a series that never finishes. If the series is then joined, grouped or sorted, the database keeps working until the exercise cuts the query off.
Treating a date like a number
SELECT day + 1 FROM days looks harmless, but in SQLite '2026-06-01' + 1 turns into the number 2027. A number always compares as smaller than text, so day < '2026-06-15' stays true forever: an infinite loop. For date series use date(day, '+1 day').
Cancelled orders filtered in WHERE
After the LEFT JOIN, a day without orders has an empty status. WHERE o.status <> 'cancelled' throws exactly those days out again, and the exercise says "Your query returns only 5 rows. Wanted: 15 rows". The condition belongs in ON.
Column missing from the CTE
The recursive part can only use columns the CTE has. Leave employee_id out of the anchor and the join has nothing to match on; the exercise reports: "o.employee_id": this column exists, but not in the table before the dot.
Joining text with +
c.path + ' / ' + e.last_name is how SQL Server writes it. SQLite treats it as arithmetic, and the exercise says "Columns and row count match, but not every value". Join text with ||.
Leaving out RECURSIVE
SQLite runs the query without the keyword, but the exercise still asks for it: "Solve this one with RECURSIVE." MySQL and PostgreSQL require it, and your query should run there too.
Recursion in MySQL, PostgreSQL, SQL Server and SQLite
| Database | Syntax | Safety limits and quirks |
|---|---|---|
| MySQL (8.0 and later) | WITH RECURSIVE, required as soon as a CTE reads itself | stops after cte_max_recursion_depth levels, 1000 by default; LIMIT in the recursive part since 8.0.19; the anchor sets the column width, so longer paths get cut off unless the anchor uses CAST(last_name AS CHAR(200)) |
| PostgreSQL | WITH RECURSIVE | CYCLE id SET is_cycle USING path detects cycles; SEARCH DEPTH FIRST or BREADTH FIRST sets the order |
| SQL Server | no RECURSIVE, just WITH; only UNION ALL between anchor and recursive part | default limit of 100 levels, change it with OPTION (MAXRECURSION n) from 0 to 32767, where 0 means no limit; data types in the recursive part must match the anchor |
| SQLite (these exercises) | WITH RECURSIVE | no fixed limit; LIMIT in the recursive part always ends the recursion, UNION drops duplicate rows |
Sources: MySQL Reference Manual (WITH), PostgreSQL documentation (WITH Queries), Microsoft Learn (WITH common_table_expression), sqlite.org (The WITH Clause, Datatypes).
FAQ
What is the difference between the anchor and the recursive part?
The anchor runs exactly once and returns the starting rows. The recursive part reads the CTE itself and runs again and again until it finds nothing new. UNION ALL connects the two.
Why UNION ALL rather than UNION?
UNION ALL is faster because the database doesn't have to remember every earlier row. UNION is worth it when the data may contain cycles and the rows look the same each round. SQL Server only allows UNION ALL between the anchor and the recursive part.
How deep can a hierarchy go?
SQLite has no fixed limit. MySQL stops at 1000 levels by default, SQL Server at 100. That is plenty for any org chart; if you hit the limit, a cycle in the data is the usual reason.
Can I do this without recursion?
Only if the depth is fixed: two self joins for three levels. Add one more level and rows go missing. That is why the exercises also run against a deeper org chart.