Recursive CTE Manager Chain Walk

Walk a manager_id chain upward with a recursive CTE: anchor on one employee, join the next manager each step, stop when manager_id is NULL.

SqlData Integrity

Code

snippet
WITH RECURSIVE employees(id, name, manager_id) AS (
    VALUES
        (1, 'ceo',  NULL::int),
        (2, 'vp',   1),
        (3, 'lead', 2),
        (4, 'dev',  3)
),
-- 向上走 manager chain:锚点是目标员工,递归步逐级接上一层
ancestors AS (
    SELECT id, name, manager_id, 0 AS hops
    FROM employees
    WHERE id = 4

    UNION ALL

    SELECT m.id, m.name, m.manager_id, a.hops + 1
    FROM ancestors a
    JOIN employees m ON m.id = a.manager_id
)
SELECT hops, name, manager_id
FROM ancestors
ORDER BY hops;
-- manager_id IS NULL 时 JOIN 落空,chain 自然到顶终止;链条成环则会无限递归

How it works

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

Concretely, the SQL combines: a CTE (WITH … AS) that names an intermediate result before the main query; one JOIN combining rows across tables; a WHERE clause limiting a statement to the rows that qualify; an ORDER BY that fixes the output order; a UNION stitching together the result sets of separate queries.

Putting it to use

Run the statement against the employees table.

Interactive Tools for This Topic

FAQ

What relations does the SQL touch?
The references are `employees`, `ancestors`, with one join tying the pair together.