Sub topic 7
Tracking Depth and Path Through the Tree
This chapter assumes that you know SELECT, WHERE, ORDER BY, self-joins, and the anchor and recursive members of a recursive common table expression (CTE). A recursive CTE can carry extra columns along each iteration. Two useful columns are depth, which records the distance from the root, and path, which records the IDs visited so far.
Why depth and path matter
Suppose an employees table stores an employee's manager:
| id | name | manager_id |
|---|---|---|
| 1 | Ada | NULL |
The row with no manager is the root. Its depth is 0. Each employee below it has a depth one greater than its manager.
A path is an ordered list of IDs from the root to the current row. For example, [1, 4, 9] means that employee 9 reports to employee 4, who reports to employee 1.
These values help you:
- indent a hierarchy for display;
- sort rows in tree order;
- show breadcrumbs such as
Ada > Ben > Chen; - detect a cycle before a query repeats forever;
- limit traversal to a safe number of levels.
Adding depth and path
The following PostgreSQL example creates a small organization and walks it. PostgreSQL arrays are convenient for storing the path.
CREATE TEMP TABLE employees (
id integer PRIMARY KEY,
name text NOT NULL,
manager_id integer REFERENCES employees(id)
);
INSERT INTO employees (id, name, manager_id) VALUES
(1, 'Ada', NULL),
(2, 'Ben', 1),
(3, 'Chen', 1),
(4, 'Dina', 2),
(5, 'Eli', 2);
WITH RECURSIVE org AS (
SELECT
id,
name,
manager_id,
0 AS depth,
ARRAY[id] AS path
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT
e.id,
e.name,
e.manager_id,
o.depth + 1,
o.path || e.id
FROM employees AS e
JOIN org AS o
ON e.manager_id = o.id
WHERE o.depth < 10
)
SELECT
id,
name,
depth,
path,
repeat(' ', depth) || name AS indented_name
FROM org
ORDER BY path;The anchor member starts each root with depth = 0 and a one-element path. The recursive member finds direct reports, adds one to the depth, and appends the employee ID with the array concatenation operator ||.
PostgreSQL compares arrays element by element when it sorts them. Therefore, ORDER BY path keeps descendants near their parent and usually produces a natural tree order.
Using the path to prevent cycles
A depth limit protects the query from traversing indefinitely, but it can hide a data problem. A path check prevents the recursive member from revisiting an ID already in the current path.
WITH RECURSIVE org AS (
SELECT
id,
name,
manager_id,
0 AS depth,
ARRAY[id] AS path
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT
e.id,
e.name,
e.manager_id,
o.depth + 1,
o.path || e.id
FROM employees AS e
JOIN org AS o
ON e.manager_id = o.id
WHERE e.id <> ALL (o.path)
AND o.depth < 100
)
SELECT id, name, depth, path
FROM org
ORDER BY path;The condition e.id <> ALL (o.path) means that the candidate employee ID must differ from every ID already visited. Keep a depth limit as a second safeguard, especially when data can be malformed.
Other databases represent paths differently. MySQL can use JSON arrays, while SQLite commonly uses a delimiter-separated text value. The idea is unchanged: carry the previous path forward, append the next node, and reject a node already present in that path.
Exercise
In the example, what are the depth and path for Eli, whose ID is 5 and whose manager is Ben, ID 2?
Show answer
Eli has depth 2 and path [1, 2, 5]. Ada is the root at depth 0, and Ben is one level below Ada.