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_idfirst_namelast_namedepartmentsalaryhire_datemanager_id
1KarenMitchellManagement936002018-01-02NULL
2TomBradleySales624002019-04-011
3JuliaReyesSales468002021-06-152
4MarcusAllenSales492002020-09-012
5SarahLongWarehouse396002022-02-011
6FelixTurnerWarehouse354002024-03-185
7NinaCooperAccounting528002019-10-011
8DavidRossCustomer service384002023-05-022
9LauraHughesCustomer serviceNULL2025-09-012
10PaulWardAccounting432002022-11-147

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;
stepfirst_namelast_name
1FelixTurner
2SarahLong
3KarenMitchell

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_idcustomer_idorder_datestatusemployee_id
100112026-01-08delivered3
100242026-01-12delivered4
100332026-01-20delivered3
100472026-02-03delivered4
100522026-02-11cancelled8
100612026-02-25delivered3
1007102026-03-04delivered2
100852026-03-17delivered4
100982026-03-30delivered3
101062026-04-07delivered8
1011122026-04-22delivered4
101232026-05-06delivered3
101392026-05-19cancelled8
101472026-06-02shipped4
101512026-06-10shipped3
1016112026-06-12openNULL
101742026-06-13openNULL
1018102026-06-14openNULL
order_items 38 rows, 4 columns
order_idproduct_idquantityunit_price
10011404.79
10013252.79
10016424.9
1002223.49
10021035.49
10031604.69
100311684.9
10033502.59
100443179
100493269
100551449
10061304.79
10067106.99
100782219
100711489.9
10071204.99
100846175
1008253.49
1009101204.99
10092403.19
100992279
1010726.99
1010213.49
1011121129
10111104.99
10113122.79
10126823.9
10121404.69
101391279
101452439
101442179
10151504.79
101511289.9
10161045.49
1017233.49
1017726.99
10181804.79
101861024.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_idfirst_namelast_namedepartmentsalaryhire_datemanager_id
1KarenMitchellManagement936002018-01-02NULL
2TomBradleySales624002019-04-011
3JuliaReyesSales468002021-06-152
4MarcusAllenSales492002020-09-012
5SarahLongWarehouse396002022-02-011
6FelixTurnerWarehouse354002024-03-185
7NinaCooperAccounting528002019-10-011
8DavidRossCustomer service384002023-05-022
9LauraHughesCustomer serviceNULL2025-09-012
10PaulWardAccounting432002022-11-147

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 <= 5 at 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

DatabaseSyntaxSafety limits and quirks
MySQL (8.0 and later)WITH RECURSIVE, required as soon as a CTE reads itselfstops 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))
PostgreSQLWITH RECURSIVECYCLE id SET is_cycle USING path detects cycles; SEARCH DEPTH FIRST or BREADTH FIRST sets the order
SQL Serverno RECURSIVE, just WITH; only UNION ALL between anchor and recursive partdefault 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 RECURSIVEno 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.

Up next: UPSERT

Create a product if it is new, and just add to the stock if it already exists: INSERT … ON CONFLICT does both in one statement. You'll also see why INSERT OR REPLACE quietly deletes data.

Practice UPSERT

Write to us

Choose language

Select your preferred language