SQL

Recursive CTE — Walk a Hierarchy

admin by @admin ADMIN
1h ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`WITH RECURSIVE` lets a CTE refer to itself. The standard way to walk parent/child trees (org charts, comment threads, category nestings) in a single query.
SQL
Raw
-- Every descendant of employee 42 in the org chart
WITH RECURSIVE reports AS (
    -- Anchor row: the starting employee
    SELECT id, name, manager_id, 0 AS depth
    FROM   employees
    WHERE  id = 42

    UNION ALL

    -- Recursive part: anyone whose manager is already in `reports`
    SELECT e.id, e.name, e.manager_id, r.depth + 1
    FROM   employees e
    JOIN   reports   r ON e.manager_id = r.id
)
SELECT id, name, depth FROM reports ORDER BY depth, name;

-- Walk a comment tree (parent_id → children)
WITH RECURSIVE thread AS (
    SELECT id, parent_id, body, 0 AS depth, ARRAY[id] AS path
    FROM   comments WHERE id = $1
    UNION ALL
    SELECT c.id, c.parent_id, c.body, t.depth + 1, t.path || c.id
    FROM   comments c
    JOIN   thread t ON c.parent_id = t.id
)
SELECT REPEAT('  ', depth) || body AS indented, path
FROM   thread
ORDER  BY path;
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.