Traversing Organizational Charts & Category Trees with Recursive CTEs
Walk manager hierarchies and nested categories with recursive CTEs.
In plain words
Start at one person or category and keep following parent or child links until there are none left.
Think of it like…
A family tree: to list someone's descendants you follow the lines downward generation by generation; to find their ancestors you follow the lines upward until you reach the top.
Where you’ve seen it
An online store's category page for "Phones" must show products from Phones and every subcategory under it: WITH RECURSIVE sub AS (SELECT id FROM categories WHERE id = 12 UNION ALL SELECT c.id FROM categories c JOIN sub ON c.parent_id = sub.id) SELECT p.* FROM products p WHERE p.category_id IN (SELECT id FROM sub); The same table builds the breadcrumb by walking up from the product's category.
Words you’ll hear
- Adjacency list
- Each row stores its parent's id; the most common way to store a tree.
- Subtree walk
- Recursing downward: children, grandchildren and so on.
- Ancestor walk
- Recursing upward from a node to the root, for breadcrumbs.
- Path array
- An array of ids from the root, used for depth, ordering and cycle checks.
Visual diagram
Theory & example queries
Down, up, depth and path
Walking down: the anchor selects the starting node, and the recursive step joins rows whose parent_id is in the previous level. Walking up: the anchor selects the starting node, and the recursive step joins the row whose id equals the current row's parent_id, stopping at the root where parent_id is NULL. Carry depth + 1 and path || id (an array) in each step.
The path array does three jobs. Its length is the depth. ORDER BY path lists the tree in display order, each parent followed by its children, ready to indent by depth. And WHERE NOT c.id = ANY(path) stops cycles if bad data ever makes a node its own ancestor. For a breadcrumb string, aggregate names along the ancestor walk ordered by depth with STRING_AGG.
WITH RECURSIVE up AS ( SELECT id, name, parent_id, 0 AS lvl FROM categories WHERE id = 31 UNION ALL SELECT c.id, c.name, c.parent_id, up.lvl + 1 FROM categories c JOIN up ON c.id = up.parent_id )SELECT STRING_AGG( name, ' › ' ORDER BY lvl DESC ) AS breadcrumbFROM up;PostgreSQL is the lesson baseline unless noted otherwise.
Read this line together with the surrounding statement as part of the same SQL expression.
Ancestor path1 sample row
| breadcrumb |
|---|
| Electronics › Phones › Android |
Note: The row assumes category 31 is named Android, with Phones as its parent and Electronics at the root; actual spelling and path depth come from the category data.
returns 'Electronics › Phones › Android'.
Key takeaway: Join on parent_id to go down, on id = parent_id to go up; carry depth and path.
Roll-ups and other ways to store trees
Roll-ups such as "total headcount under each manager, including indirect reports" need every (ancestor, descendant) pair. Generate them by keeping the starting id as a column: anchor SELECT id AS root, id AS node FROM employees, recursive step joins children of node and keeps root. Then GROUP BY root counts descendants or sums their values. On large trees this is expensive, which is why roll-ups are often precomputed.
If a tree is read far more than it changes, alternative models avoid recursion at query time. A materialised path stores '1.12.31' on each row (PostgreSQL's ltree type indexes it, so path <@ '1.12' finds a subtree). A closure table stores every ancestor-descendant pair with its depth, so subtrees and roll-ups are plain joins, at the cost of extra rows to maintain when nodes move. Nested sets make reads fast but writes very expensive.
WITH RECURSIVE pairs AS ( SELECT id AS manager_id, id AS employee_id FROM employees UNION ALL SELECT p.manager_id, e.id FROM employees e JOIN pairs p ON e.manager_id = p.employee_id )SELECT manager_id, COUNT(*) - 1 AS reportsFROM pairsGROUP BY manager_id;PostgreSQL is the lesson baseline unless noted otherwise.
Read this line together with the surrounding statement as part of the same SQL expression.
Representative reporting counts3 sample rows
| manager_id | reports |
|---|---|
| 10 | 8 |
| 11 | 3 |
| 24 | 0 |
Note: Sample values assume manager 10 has eight descendants, manager 11 has three, and employee 24 has none. The calculation counts all levels, not only direct reports.
The -1 excludes the manager themselves.
Key takeaway: Generate (root, node) pairs for roll-ups; use ltree or closure tables for read-heavy trees.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Choose the direction
Down for subtrees (team, subcategories), up for ancestors (breadcrumb, approval chain), pairs for roll-ups.
down · up · pairs
When to use it & trade-offs
What it is
Hierarchies like org charts and product categories are usually stored as an adjacency list: each row has a parent_id pointing to its parent. Recursive CTEs answer the everyday questions about them: everything below a node (a manager's whole team, a category's subcategories), everything above a node (the breadcrumb Electronics › Phones › Android), each node's depth and path, and totals rolled up through the tree.
Why it matters: Breadcrumbs, "products in this category including subcategories", headcount per manager and permission inheritance all need tree walks. Writing them correctly, with depth, ordering and protection against bad data, is a practical skill, and knowing when to switch to a different tree storage model (materialised path, closure table) is a common senior design question.
When to reach for it
- Breadcrumbs and category pages including subcategories
- Org charts, reporting lines and approval chains
- Threaded comments and folder trees
When to avoid or be careful
- Recursive walks without an index on parent_id
- Recursion without a cycle guard on user-editable trees
- Recomputing large roll-ups on every page view
Ways to store a hierarchy
Strengths: Simple writes (change one parent_id); flexible queries.
Watch out: Every subtree or ancestor query recurses.
Strengths: Indexed subtree and ancestor checks without recursion.
Watch out: Moving a subtree rewrites every descendant's path.
Strengths: Subtrees, ancestors and depths are plain joins.
Watch out: Many extra rows; inserts and moves must update pairs.
Interview signals & numbers to know
When this topic comes up
- “Show all products in this category and its subcategories”
- “Build a breadcrumb”
- “Total headcount under each manager”
- Tree storage design
- Threaded comments
Benchmarks & rules of thumb
- NULL parent_id
- marks the root
- COUNT(*) − 1
- descendants, excluding the node itself
- 1 row per pair
- in a closure table
Common mistakes & follow-ups
Common interview mistakes
- Joining on c.id = t.parent_id when you meant to walk down, and getting ancestors instead of children.
- Ordering a tree by name instead of path, so children aren't listed under their parents.
- Running a recursive headcount over 200,000 employees on every dashboard load instead of precomputing it.
Likely interviewer follow-ups
- Write a query that returns the breadcrumb for a category.
- How would you count all direct and indirect reports for every manager?
- When would you choose a closure table over an adjacency list?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Traversing Organizational Charts & Category Trees with Recursive CTEs with hands-on SQL practice and interview Q&A.