← All SQL interview questions
Walk the category tree and report its depth
HardRecursive CTEsAmazonMyntra
A catalogue team maintains categories as a parent-child tree in catalog_categories. Root categories have a NULL parent.
Using a recursive CTE, return category_id, category_name, depth (1 for roots, 2 for their children, and so on) and path — the names from the root down to that category joined with > .
Sample data
Table: catalog_categories
15 row(s) · showing first 8
| category_idINT | category_nameTEXT | parent_idINT |
|---|---|---|
| 1 | Home & Kitchen | NULL |
| 2 | Apparel | NULL |
| 3 | Cookware | 1 |
| 4 | Storage | 1 |
| 5 | Pans | 3 |
| 6 | Pressure Cookers | 3 |
| 7 | Non-stick Pans | 5 |
| 8 | Cast Iron Pans | 5 |
catalog_categories
- category_idINT
- category_nameTEXT
- parent_idINT
- Step 1: Write the **anchor member**: every row whose `parent_id IS NULL` is a root, gets `depth = 1` and a `path` equal to its own name.
- Step 2: Write the **recursive member**: join `catalog_categories` back to the CTE on `t.category_id = c.parent_id` so each iteration attaches the children of the rows found so far.
- Step 3: Carry the accumulators forward — `t.depth + 1` increments the level and `t.path || ' > ' || c.category_name` appends to the breadcrumb.
- Step 4: Combine the two members with `UNION ALL`. Postgres repeats the recursive step until it produces no new rows.
- Step 5: Select from the CTE in the outer query. `WITH RECURSIVE` is required even though only one member recurses.
WITH RECURSIVE tree AS (
SELECT category_id,
category_name,
1 AS depth,
category_name AS path
FROM catalog_categories
WHERE parent_id IS NULL
UNION ALL
SELECT c.category_id,
c.category_name,
t.depth + 1,
t.path || ' > ' || c.category_name
FROM catalog_categories AS c
INNER JOIN tree AS t ON t.category_id = c.parent_id
)
SELECT category_id, category_name, depth, path
FROM tree;Learn the concept first
Stuck on Recursive CTEs? These free SQL lessons teach it step by step.
More Recursive CTEs questions
Practising alone only goes so far — our live cohorts pair SQL depth with dashboards, agentic analytics projects and mock interviews.
Explore the program