Recursive CTE for an Org Chart

Walk a self-referencing employee table with a recursive CTE to list each person and their management depth from the top.

SqlData Integrity

Code

sqlsnippet
24 lines
WITH RECURSIVE org_chart AS (
    SELECT
        id,
        name,
        manager_id,
        1 AS depth,
        name AS path
    FROM employees
    WHERE manager_id IS NULL

    UNION ALL

    SELECT
        e.id,
        e.name,
        e.manager_id,
        oc.depth + 1,
        oc.path || ' > ' || e.name
    FROM employees e
    JOIN org_chart oc ON e.manager_id = oc.id
)
SELECT id, name, depth, path
FROM org_chart
ORDER BY path;

Inside the snippet

What runs is SELECT, with employees and org_chart as the object involved.

In terms of clauses, the statements use: a CTE (WITH … AS) that names an intermediate result before the main query; one JOIN combining rows across tables; a WHERE clause constraining which rows the statement operates on; an ORDER BY that fixes the output order; a UNION stitching together the result sets of separate queries.

Putting it to use

The employees table is the working surface here.

Interactive Tools for This Topic

FAQ

What are the relations in play here?
The references are `employees`, `org_chart`, with one join tying the pair together.