Sub topic 7
Walking an Organization Chart or Category Tree
A parent-child hierarchy stores each row with a reference to its parent. An organization chart is one example: an employee has a manager_id that points to another employee. A product category tree works the same way: a category has a parent_id that points to another category.
This chapter assumes you know SELECT, JOIN, WHERE, ORDER BY, and basic CTE syntax. You should also be comfortable reading a table where one column refers to another row in the same table.
Model the hierarchy
Suppose employees has these columns:
id: the employee's unique identifiername: the employee's namemanager_id: the identifier of the employee's managermanager_id IS NULL: this employee is at the top of the organization
A recursive CTE starts with one or more known rows and repeatedly finds related rows. The first query is the anchor member. It finds the starting rows. The second query is the recursive member. It finds the next level from rows already discovered.
Start at the top and move downward
The following query returns every employee below the top-level employees. The depth column records the distance from the top.
WITH RECURSIVE org AS (
-- Anchor member: find the top-level employees.
SELECT
id,
name,
manager_id,
0 AS depth
FROM employees
WHERE manager_id IS NULL
UNION ALL
-- Recursive member: find direct reports.
SELECT
e.id,
e.name,
e.manager_id,
o.depth + 1
FROM employees AS e
JOIN org AS o
ON e.manager_id = o.id
)
SELECT id, name, manager_id, depth
FROM org
ORDER BY depth, name;The database evaluates this in rounds:
- The anchor member returns the top-level employees at depth
0. - The recursive member finds employees whose
manager_idmatches those employees. - Those employees receive depth
1. - The process repeats for the next level.
- Recursion ends when a round finds no new matching rows.
UNION ALL keeps every row produced by the traversal. It is normally used for recursive CTEs because the query itself controls which rows are visited.
A hierarchy can have more than one root. For example, a company might have two independent divisions. The manager_id IS NULL condition includes all of them.
Keep the path to each row
Depth tells you how far a row is from the root, but a path can show the complete chain of managers. In PostgreSQL, an array can store the identifiers visited so far.
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)
)
SELECT
id,
name,
depth,
path
FROM org
ORDER BY path;The path value might be {1,4,9}. It means the traversal started at employee 1, then visited employee 4, and then employee 9.
The condition e.id <> ALL (o.path) prevents the recursive member from visiting an employee already present in the current path. This protects the query if bad data creates a cycle, such as employee 1 managing employee 2 while employee 2 manages employee 1.
Apply the same pattern to categories
A category table can use the same structure:
idnameparent_id
To list every category below the category with ID 10, change the anchor and join:
WITH RECURSIVE category_tree AS (
SELECT
id,
name,
parent_id,
0 AS depth
FROM categories
WHERE id = 10
UNION ALL
SELECT
c.id,
c.name,
c.parent_id,
t.depth + 1
FROM categories AS c
JOIN category_tree AS t
ON c.parent_id = t.id
)
SELECT id, name, parent_id, depth
FROM category_tree
ORDER BY depth, name;This query includes category 10 itself, then its children, grandchildren, and so on. To start with every root category instead, use WHERE parent_id IS NULL in the anchor member.
Exercise
In the employee query, what changes are needed to return only employees at most three levels below a root?
Show answer
Add WHERE o.depth < 3 to the recursive member. Since the recursive member creates the next depth as o.depth + 1, the query will return depths 0 through 3.