Skip to content
KALANBLON
Show contents

Chapter 2 of 7 · 20 min

Recursive CTEs: trees and graphs

By the end of this chapter, you'll be able to

  • Write a recursive CTE with an initial part and a recursive part
  • Walk a hierarchy from top to bottom and from bottom to top
  • Explore a graph while avoiding cycles
  • Generate a sequence of values or dates

The principle

A recursive CTE (WITH RECURSIVE) has two parts joined by UNION ALL: an initial query, which produces the first rows, and a recursive query, which starts from the rows produced at the previous step to produce new ones. SQLite repeats until a step produces nothing.

WITH RECURSIVE counter(n) AS (
  SELECT 1
  UNION ALL
  SELECT n + 1 FROM counter WHERE n < 5
)
SELECT n, n * n AS square FROM counter;
n | square
1 | 1
2 | 4
3 | 9
4 | 16
5 | 25

The CTE's result is the union of all the rows produced.

Step 5 of 5
Text description of the animation
  1. The initial query produces the first row.
  2. The first round starts from 1 and produces 2.
  3. Each round starts only from the rows produced by the previous round.
  4. For n = 5, the condition n < 5 is false: the round produces nothing, the recursion stops.
  5. The CTE's result is the union of all the rows produced.

Walking a hierarchy

In the employees table, each person has a manager_id pointing to their manager; the director has none (NULL). To display the whole org chart, start from the root, then each round adds the reports of the people found in the previous round:

WITH RECURSIVE team(id, name, role, level, path) AS (
  SELECT id, name, role, 0, name FROM employees WHERE manager_id IS NULL
  UNION ALL
  SELECT e.id, e.name, e.role, t.level + 1, t.path || ' > ' || e.name
  FROM employees AS e
  JOIN team AS t ON e.manager_id = t.id
)
SELECT substr('            ', 1, level * 2) || name AS org_chart, role, path
FROM team
ORDER BY path;
org_chart | role | path
Nadia | director | Nadia
  Omar | technical lead | Nadia > Omar
    Quentin | developer | Nadia > Omar > Quentin
      Sami | intern | Nadia > Omar > Quentin > Sami
    Rania | developer | Nadia > Omar > Rania
  Paula | sales lead | Nadia > Paula
    Tess | sales rep | Nadia > Paula > Tess
  • The level column goes up by 1 each round: it's used to indent the names.
  • The path column accumulates the names from the root; sorting on it places each person under their manager.
  • || concatenates texts; substr(text, 1, n) keeps its first n characters.

For a subtree, just change the starting point:

WITH RECURSIVE below(id, name) AS (
  SELECT id, name FROM employees WHERE name = 'Omar'
  UNION ALL
  SELECT e.id, e.name FROM employees AS e JOIN below ON e.manager_id = below.id
)
SELECT COUNT(*) - 1 AS people_under_omar, GROUP_CONCAT(name, ', ') AS team FROM below;
people_under_omar | team
3 | Omar, Quentin, Rania, Sami

Exploring a graph

The routes table describes bus journeys between cities in Mali, with their duration. A graph can contain cycles (Ségou → Mopti → Ségou): the query must be prevented from going round in circles. Here, we refuse to add a city already present in the route:

WITH RECURSIVE trips(city, route, duration, legs) AS (
  SELECT 'Bamako', 'Bamako', 0.0, 0
  UNION ALL
  SELECT r.destination, t.route || ' → ' || r.destination, t.duration + r.hours, t.legs + 1
  FROM trips AS t
  JOIN routes AS r ON r.origin = t.city
  WHERE instr(t.route, r.destination) = 0
)
SELECT route, duration
FROM trips
WHERE city = 'Timbuktu'
ORDER BY duration;
route | duration
Bamako → Ségou → Mopti → Timbuktu | 17.5
Bamako → Sikasso → Mopti → Timbuktu | 22.5

instr(route, city) returns the position of city in the text route, or 0 if it isn't there. It's a simple solution for a small graph; a real application would store the identifiers of the visited cities, so that a city name contained in another doesn't skew the test.

Your turn

Mini-lab: a calendarSQLite

Result

Click “Run”: the SQL engine (about 1 MB) will load in your browser the first time.

A fresh SQLite database is created on every run, in your browser · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Worked exercise

Solved exercise: the chain of command

Sami, an intern, wants to know who to escalate a request to. Display the chain of his managers, from him up to the director, with each person's level (0 for Sami).

Hint 1
This time, you go up the tree: the initial query selects Sami, and each round looks for the employee whose id equals the previous row's manager_id.
Hint 2
The recursion stops by itself: the director has a NULL manager_id, which matches no id.
Show the solution and common mistakes
WITH RECURSIVE bosses(id, name, manager_id, level) AS (
  SELECT id, name, manager_id, 0 FROM employees WHERE name = 'Sami'
  UNION ALL
  SELECT e.id, e.name, e.manager_id, b.level + 1
  FROM employees AS e JOIN bosses AS b ON e.id = b.manager_id
)
SELECT level, name FROM bosses ORDER BY level;
level | name
0 | Sami
1 | Quentin
2 | Omar
3 | Nadia

The only difference from the org chart is the join condition: e.id = b.manager_id (going up) instead of e.manager_id = t.id (going down).

Common mistakes:

  • Reversing the join condition: you get Sami's reports (none), and the result contains only him.
  • Using UNION instead of UNION ALL: here the result is the same, but UNION removes duplicates at every round, which costs more and can hide a modelling error.

Summary

  1. 1WITH RECURSIVE combines an initial query and a recursive query with UNION ALL.
  2. 2Each round starts from the rows produced by the previous round; recursion stops when a round produces nothing.
  3. 3You go down a hierarchy with e.manager_id = parent.id, and up with e.id = child.manager_id.
  4. 4In a graph with cycles, refuse to revisit a node, or the query never stops.
  5. 5A recursive CTE also generates sequences of numbers or dates.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.