Reading history

Hierarchical Data in SQL: Trees and Recursive Queries

6 min read 0 views

Query tree data in SQL with recursive CTEs: org charts, paths and depth, ancestors, subtree totals, loop protection and other ways to store a tree.

Many kinds of data form a tree: employees and managers, categories and sub-categories, folders inside folders, replies to comments. The usual way to store a tree in SQL is a column that points to the parent row. Reading the tree back, with every level, needs a recursive query. This lesson shows how to draw the whole tree, walk up from a single row, total a manager’s whole team and protect a query from loops in bad data.

In this lesson you will learn

  • Storing a tree with a parent column (an adjacency list)
  • Walking down a tree and building each row’s path and depth
  • Walking up a tree to find every ancestor
  • Totals over a whole subtree
  • Stopping a recursive query when the data contains a loop

You should know the basics of recursive queries from Common Table Expressions and self joins. The examples use the sample employees table, where manager_id points to another employee.

Walking Down: The Whole Org Chart

-- Walk the org chart from the top, building each person's path
WITH RECURSIVE chart(id, name, depth, path) AS (
  SELECT id, name, 0, name
  FROM employees
  WHERE manager_id IS NULL
  UNION ALL
  SELECT e.id, e.name, c.depth + 1, c.path || ' > ' || e.name
  FROM employees e
  JOIN chart c ON e.manager_id = c.id
)
SELECT substr('            ', 1, depth * 4) || name AS tree, depth, path
FROM chart
ORDER BY path;

-- Everyone above Sumi (walk upwards)
WITH RECURSIVE up(id, name, manager_id) AS (
  SELECT id, name, manager_id FROM employees WHERE name = 'Sumi'
  UNION ALL
  SELECT e.id, e.name, e.manager_id
  FROM employees e JOIN up ON e.id = up.manager_id
)
SELECT name FROM up WHERE name <> 'Sumi';

Output

+------------------+-------+---------------------------------+
| tree             | depth | path                            |
+------------------+-------+---------------------------------+
| Shahana          | 0     | Shahana                         |
|     Faisal       | 1     | Shahana > Faisal                |
|         Mou      | 2     | Shahana > Faisal > Mou          |
|         Rubel    | 2     | Shahana > Faisal > Rubel        |
|             Sumi | 3     | Shahana > Faisal > Rubel > Sumi |
|     Lipi         | 1     | Shahana > Lipi                  |
|         Anik     | 2     | Shahana > Lipi > Anik           |
+------------------+-------+---------------------------------+
(7 rows)

+---------+
| name    |
+---------+
| Rubel   |
| Faisal  |
| Shahana |
+---------+
(3 rows)
  • The anchor part selects the starting rows: the employee with no manager, Shahana, at depth 0.
  • The recursive part joins employees to the rows found so far (e.manager_id = c.id), adding 1 to the depth and extending the path. It repeats until a round finds no new rows.
  • Sorting by the path string puts each person directly under their manager, and indenting by depth turns the result into a readable tree.
  • The second query walks the other way. It starts at Sumi and repeatedly joins to the manager (e.id = up.manager_id), giving her chain of command: Rubel, Faisal and Shahana.

Totals Over a Subtree, and Loops

-- Total salary cost of each manager's whole team (the subtree)
WITH RECURSIVE team(root, id) AS (
  SELECT id, id FROM employees
  UNION ALL
  SELECT t.root, e.id
  FROM employees e JOIN team t ON e.manager_id = t.id
)
SELECT r.name AS manager,
       COUNT(*) - 1 AS people_below,
       SUM(e.salary) AS team_cost
FROM team t
JOIN employees r ON r.id = t.root
JOIN employees e ON e.id = t.id
GROUP BY t.root
HAVING COUNT(*) > 1
ORDER BY team_cost DESC;

-- Guard against bad data: a loop (A manages B, B manages A)
UPDATE employees SET manager_id = 7 WHERE id = 4;    -- Rubel now reports to his own intern
WITH RECURSIVE chain(id, path, depth) AS (
  SELECT id, '/' || id || '/', 0 FROM employees WHERE id = 7
  UNION ALL
  SELECT e.manager_id, c.path || e.manager_id || '/', c.depth + 1
  FROM chain c JOIN employees e ON e.id = c.id
  WHERE e.manager_id IS NOT NULL
    AND instr(c.path, '/' || e.manager_id || '/') = 0   -- stop when we revisit someone
)
SELECT path, depth FROM chain ORDER BY depth DESC LIMIT 1;

Output

+---------+--------------+-----------+
| manager | people_below | team_cost |
+---------+--------------+-----------+
| Shahana | 6            | 880000    |
| Faisal  | 3            | 390000    |
| Lipi    | 1            | 240000    |
| Rubel   | 1            | 115000    |
+---------+--------------+-----------+
(4 rows)

+-------+-------+
| path  | depth |
+-------+-------+
| /7/4/ | 1     |
+-------+-------+
(1 row)
  • The team CTE starts every employee as their own root, then adds everyone below them. The result is one row for every (manager, person in their subtree) pair, including the manager.
  • Grouping by root gives each manager’s head count and total salary cost. Faisal’s 390,000 is his own 180,000 plus Mou, Rubel and Sumi. HAVING COUNT(*) > 1 hides people with nobody below them.
  • Next, the data is broken on purpose: Rubel now reports to Sumi, who reports to Rubel. A recursive query that follows managers would go round this loop for ever.
  • The guard keeps a path of visited ids such as /7/4/ and stops when the next id is already in it (instr(...) = 0). The walk from Sumi stops after one step instead of looping.

Some databases have built-in loop protection, such as the CYCLE clause in PostgreSQL 14+. A depth limit (WHERE depth < 20) is another simple safety net.

Other Ways to Store a Tree

ModelHow it worksGood atWeak at
Adjacency list (this lesson)Each row stores its parent’s idSimple; easy to insert and move rowsReading a whole subtree needs recursion
Path columnEach row stores its full path, such as /1/2/4/Subtree is a simple LIKE '/1/2/%'Moving a branch means rewriting many paths
Closure tableA separate table stores every ancestor–descendant pairFast subtree and ancestor queriesExtra table to keep in sync

Common Mistakes

  1. Joining in the wrong direction. e.manager_id = c.id walks down; e.id = c.manager_id walks up.
  2. Forgetting the anchor filter, so every employee becomes a starting point and rows repeat.
  3. No protection against loops when the data is not guaranteed to be a clean tree.
  4. Using UNION instead of UNION ALL without thinking. UNION removes duplicate rows, which can hide mistakes and costs extra time.

Practice Exercises

Exercise 1. List everyone who reports to Faisal, directly or indirectly, with their depth below him.

Show answer
WITH RECURSIVE below(id, name, depth) AS (
  SELECT id, name, 0 FROM employees WHERE name = 'Faisal'
  UNION ALL
  SELECT e.id, e.name, b.depth + 1
  FROM employees e JOIN below b ON e.manager_id = b.id
)
SELECT name, depth FROM below WHERE depth > 0;

The result is Rubel and Mou at depth 1, and Sumi at depth 2.

Exercise 2. Find the deepest level in the org chart.

Show answer

Use the first query’s CTE and select MAX(depth) from chart. The answer is 3 (Sumi).

Frequently Asked Questions

Does MySQL support recursive queries?

Yes, from MySQL 8.0 with WITH RECURSIVE. SQL Server supports recursive CTEs too but writes them with plain WITH, without the word RECURSIVE.

How deep can a recursive query go?

SQLite has no fixed limit. SQL Server stops at 100 levels by default (change it with OPTION (MAXRECURSION n)), and MySQL stops at 1,000 (cte_max_recursion_depth).

Summary

  • A parent-id column is the simplest way to store a tree.
  • A recursive CTE walks down (children) or up (ancestors) one level per round.
  • Build a path and depth column to sort and indent the tree.
  • Keep a visited path or a depth limit to stop loops in bad data.

Next: Gaps and Islands in SQL.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *