Sub topic 7
Tracking depth and path through the tree
This chapter assumes you can write a basic recursive CTE (anchor member, recursive member, UNION ALL) and know that the database builds the result one iteration at a time. The examples use PostgreSQL. The dialect notes show what changes elsewhere.
Why carry extra columns
A plain traversal tells you which rows belong to a tree. It does not tell you where each row sits. Two small additions answer that:
- Depth is the number of steps from a starting row to the current row. It lets you indent output, filter by level, or stop at a fixed number of levels.
- Path is the list of rows passed through on the way to the current row. It lets you print a breadcrumb such as
Ava > Ben > Dev, sort rows into tree order, and detect when a walk revisits a node.
Both are ordinary columns. The anchor member sets their starting values. The recursive member computes each new value from the parent row's value in the previous iteration.
The sample data
The examples use this small org chart.
CREATE 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, 'Ava', NULL),
(2, 'Ben', 1),
(3, 'Cara', 1),
(4, 'Dev', 2),
(5, 'Elena', 2),
(6, 'Femi', 3),
(7, 'Gus', 4);Depth: a counter column
The anchor gives the root a depth of 0. Each recursive step adds 1 to the parent's depth.
WITH RECURSIVE chain AS (
SELECT id, name, manager_id, 0 AS depth
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT e.id, e.name, e.manager_id, c.depth + 1
FROM employees e
JOIN chain c ON e.manager_id = c.id
)
SELECT id, name, depth
FROM chain
ORDER BY depth, name;Each iteration produces exactly one level of the tree. In iteration n of the recursion, every new row has depth n. This holds for a tree where each node has one parent. It does not hold for a graph where a node can be reached by routes of different lengths, as the edge cases section explains.
Choose 0 or 1 for the root and use it consistently. Starting at 0 means depth equals the number of edges from the root. Starting at 1 means depth equals the level number. Either works. Mixing them in the same codebase causes off-by-one bugs.
Path: a breadcrumb column
A path column accumulates one value per step. The anchor starts the path with the root. The recursive member appends the current row.
PostgreSQL arrays are the cleanest way to hold a path, because the path stays a list of separate values instead of one string that you have to split later.
WITH RECURSIVE chain AS (
SELECT id, name, 0 AS depth, ARRAY[name] AS path
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 chain c ON e.manager_id = c.id
)
SELECT repeat(' ', depth) || name AS tree,
depth,
array_to_string(path, ' > ') AS breadcrumb
FROM chain
ORDER BY path;The result:
tree | depth | breadcrumb
------------+-------+----------------------
Ava | 0 | Ava
Ben | 1 | Ava > Ben
Dev | 2 | Ava > Ben > Dev
Gus | 3 | Ava > Ben > Dev > Gus
Elena | 2 | Ava > Ben > Elena
Cara | 1 | Ava > Cara
Femi | 2 | Ava > Cara > FemiThree things happen in this query.
ARRAY[name]in the anchor creates a one-element array.c.path || e.nameappends an element in the recursive member.repeat(' ', depth)turns the depth number into indentation, so the flat result reads as a tree.ORDER BY pathputs every parent directly before its children. This is the main use of a path column. The next section explains why it works.
Why sorting by path gives tree order
PostgreSQL compares arrays element by element, from the first element. When one array is a prefix of another, the shorter one sorts first. So {Ava,Ben} sorts before {Ava,Ben,Dev}, and {Ava,Ben,Dev,Gus} sorts before {Ava,Ben,Elena}, because Dev is less than Elena at the third position. The result is a depth-first, pre-order listing. The path therefore also controls the order of siblings: this query lists them alphabetically by name.
Sorting by depth instead gives a breadth-first listing, one level at a time. Neither order is guaranteed unless you write an ORDER BY. A recursive CTE returns rows in no promised order.
Paths as strings
Arrays are PostgreSQL-specific in this form. MySQL, SQLite, and SQL Server do not have an equivalent array type, so paths there are built as strings. This works, but it brings three problems.
- The delimiter can appear in the data. A name that contains
>makes the breadcrumb ambiguous. Build paths from ids, which cannot contain the delimiter, and look up names in a final join if you need them. - Text sorting of ids is not numeric. The string
'1/10'sorts before'1/2'. If you sort by an id path, pad each id to a fixed width, for examplelpad(id::text, 6, '0')in PostgreSQL. - Collation can change the order. Some locale collations ignore punctuation when comparing strings, so
ORDER BYon a string path may not give tree order. Padded numeric ids avoid this, because digits and the delimiter then sort the same way in every collation.
An id path string in PostgreSQL looks like this:
WITH RECURSIVE chain AS (
SELECT id, name, 0 AS depth,
lpad(id::text, 6, '0') AS sort_key
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT e.id, e.name, c.depth + 1,
c.sort_key || '/' || lpad(e.id::text, 6, '0')
FROM employees e
JOIN chain c ON e.manager_id = c.id
)
SELECT repeat(' ', depth) || name AS tree, sort_key
FROM chain
ORDER BY sort_key;This sorts siblings by id rather than by name. To sort siblings by name, you need the name in the key, which brings back the delimiter and collation issues. The array form avoids them.
Dialect notes for string paths
In SQL Server and MySQL, the data type of each column in the recursive result comes from the anchor member. A path that starts as the short string Ava gets a narrow type, and the longer values built later no longer fit. SQL Server then raises a type-mismatch error between anchor and recursive member. MySQL truncates the value or raises a "data too long" error, depending on the SQL mode. The fix is to cast the anchor to a wide type.
SQL Server uses + for concatenation and no RECURSIVE keyword:
WITH chain AS (
SELECT id, name, manager_id, 0 AS depth,
CAST(name AS varchar(400)) AS path
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT e.id, e.name, e.manager_id, c.depth + 1,
CAST(c.path + ' > ' + e.name AS varchar(400))
FROM employees e
JOIN chain c ON e.manager_id = c.id
)
SELECT depth, path
FROM chain
ORDER BY path;In MySQL 8, use CAST(name AS CHAR(400)) in the anchor and CONCAT(c.path, ' > ', e.name) in the recursive member. In SQLite, || concatenation works as in PostgreSQL, and no cast is needed because SQLite columns do not have fixed widths.
Using depth to limit the walk
Depth also acts as a brake. Adding a condition on depth to the recursive member stops the recursion at a chosen level:
WITH RECURSIVE chain AS (
SELECT id, name, 0 AS depth
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT e.id, e.name, c.depth + 1
FROM employees e
JOIN chain c ON e.manager_id = c.id
WHERE c.depth < 2
)
SELECT name, depth FROM chain ORDER BY depth, name;This returns everyone down to depth 2 and leaves out Gus. The test belongs in the recursive member's WHERE, not the outer query. Filtering in the outer query still lets the recursion run to the bottom of the tree before throwing rows away. A depth cap is also a cheap safety net against runaway recursion, but it cannot tell a cycle from a deep tree. It simply cuts off after the limit, so a cyclic graph would still produce repeated rows up to that depth. Cycle detection with the path is the subject of a later chapter.
Edge cases
- Several roots. If more than one row has
manager_id IS NULL, each root starts its own depth-0 branch. Paths stay separate, and sorting by path groups each tree together. - Starting from a chosen node. If the anchor selects a middle node, such as
WHERE id = 2, depth and path are relative to that node, not to the top of the company. - Walking upward. To list a person's chain of managers, join the other way:
ON e.id = c.manager_id. Depth then counts levels above the start row. A path built this way reads from the employee up to the root. - Graphs. When a node can be reached by more than one route, it appears once per route, each with its own depth and path. Depth is then the length of that particular route, not a property of the node. Use
MIN(depth)in a final aggregate if you want the shortest route. - Depth and path are redundant. In PostgreSQL,
depthequalscardinality(path) - 1. Keeping a separate counter is cheaper than measuring the array each time and reads more clearly.
Exercise
Using the employees table above, write a PostgreSQL query that lists each employee with a column reports_to_chain showing the names from the root down to that employee, for example Ava > Ben > Dev, and sorts the rows so that each manager appears immediately before their own reports. Which expression in the query produces the correct row order?
Show answer
Build the path as a text array in the anchor (ARRAY[name]), append e.name in the recursive member (c.path || e.name), and in the outer query select array_to_string(path, ' > ') AS reports_to_chain with ORDER BY path. The ORDER BY path expression produces the order, because arrays compare element by element and a shorter array that is a prefix of a longer one sorts first. This places each manager before the manager's reports.
Exercise
A colleague builds a path in SQL Server with SELECT id, name, 0 AS depth, name AS path in the anchor and c.path + ' > ' + e.name in the recursive member. The query fails or truncates the path. Why, and how do you fix it?
Show answer
In SQL Server the column types of the recursive result come from the anchor member. The path column takes the type and length of name, and the recursive member's longer concatenated string does not match that type, which raises an error. The fix is to cast the anchor to a wide type, for example CAST(name AS varchar(400)) AS path, and cast the concatenation in the recursive member to the same type.