Interview question
Flatten a category tree with a recursive CTE
Uses a recursive CTE to return hierarchy depth and a readable root-to-node path.
TL;DR
Uses a recursive CTE to return hierarchy depth and a readable root-to-node path.
Recursive CTEs, anchor and recursive members, path construction, depth limits, and hierarchy assumptions.
Practice the problem like a real interview: restate, reason, implement, and test.
Table: Categories(CategoryId, ParentCategoryId, Name). Root rows have a null parent. Return CategoryId, ParentCategoryId, Depth, and a path such as Electronics > Laptops > Business.
Move to the linked follow-up, next path step, prerequisite, or deeper variant.
Practice the next layer of the same subject.
Electronics is a root, Laptops is its child, and Business is below Laptops. Their depths are 0, 1, and 2, and the Business path includes all three names.
The anchor member selects roots and initializes depth and path. The recursive member joins children to the previous level and extends both values. I cast the anchor path to a stable type because recursive CTE columns must have compatible types. A self-referencing foreign key protects parent existence, while cycle prevention needs an additional write rule.
WITH CategoryTree AS
(
SELECT
c.CategoryId,
c.ParentCategoryId,
0 AS Depth,
CONVERT(nvarchar(2000), c.Name) AS CategoryPath
FROM dbo.Categories AS c
WHERE c.ParentCategoryId IS NULL
UNION ALL
SELECT
child.CategoryId,
child.ParentCategoryId,
parent.Depth + 1,
CONVERT(
nvarchar(2000),
parent.CategoryPath + N' > ' + child.Name
) AS CategoryPath
FROM dbo.Categories AS child
INNER JOIN CategoryTree AS parent
ON parent.CategoryId = child.ParentCategoryId
)
SELECT CategoryId, ParentCategoryId, Depth, CategoryPath
FROM CategoryTree
ORDER BY CategoryPath
OPTION (MAXRECURSION 100);
An index on ParentCategoryId supports finding children at each level. Recursive traversal is appropriate for moderate trees and occasional reads; heavily queried navigation may justify a closure table, hierarchy path, or cached read model.
Spot a weak answer, missing edge case, or clearer explanation? Send it in.