Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 71/ 160
04. Subqueries & Common Table Expressions (CTEs)

Traversing Organizational Charts & Category Trees with Recursive CTEs

Walk manager hierarchies and nested categories with recursive CTEs.

AdvancedHierarchy Walk · Path / Depth3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

Breadcrumb for category 31Query example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1WITH RECURSIVE2  up AS (3    SELECT4      id,5      name,6      parent_id,7      0 AS lvl8    FROM9      categories10    WHERE11      id = 3112    UNION ALL13    SELECT14      c.id,15      c.name,16      c.parent_id,17      up.lvl + 118    FROM19      categories c20      JOIN up ON c.id = up.parent_id21  )22SELECT23  STRING_AGG(24    name,25    ' › '26    ORDER BY27      lvl DESC28  ) AS breadcrumb29FROM30  up;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · SQL expression

Read this line together with the surrounding statement as part of the same SQL expression.

1/30
3OutputInspect the representative rows, affected-row count, plan, or command status.
Ancestor path1 sample row
Ancestor path
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.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

Headcount under each managerQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1WITH RECURSIVE2  pairs AS (3    SELECT4      id AS manager_id,5      id AS employee_id6    FROM7      employees8    UNION ALL9    SELECT10      p.manager_id,11      e.id12    FROM13      employees e14      JOIN pairs p ON e.manager_id = p.employee_id15  )16SELECT17  manager_id,18  COUNT(*) - 1 AS reports19FROM20  pairs21GROUP BY22  manager_id;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · SQL expression

Read this line together with the surrounding statement as part of the same SQL expression.

1/22
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative reporting counts3 sample rows
Representative reporting counts
manager_idreports
108
113
240

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.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

The -1 excludes the manager themselves.

Key takeaway: Generate (root, node) pairs for roll-ups; use ltree or closure tables for read-heavy trees.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Question

Choose the direction

Down for subtrees (team, subcategories), up for ancestors (breadcrumb, approval chain), pairs for roll-ups.

Focus at this step

down · up · pairs

What to watch at this step
Same table
all three
Tip: use ← → to move between steps

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

Adjacency list + recursive CTE
Best for: Most apps; trees that change often

Strengths: Simple writes (change one parent_id); flexible queries.

Watch out: Every subtree or ancestor query recurses.

Materialised path (ltree)
Best for: Read-heavy category trees

Strengths: Indexed subtree and ancestor checks without recursion.

Watch out: Moving a subtree rewrites every descendant's path.

Closure table
Best for: Frequent roll-ups and deep trees

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?
Interview tip: Show the downward walk, then flip the join for the breadcrumb. Mentioning ltree or closure tables for read-heavy trees shows you think about the design, not just the query.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
Recursive CTEs Fundamentals (Anchor Member + Recursive Member)
Next topic
Generating Calendars, Date Spines & Number Sequences with Recursive CTEs