Two Recursive CTEs In One Query

One WITH list may hold several RECURSIVE items: walk the manager chain upward and fan out to all reports in the same query, then union the labeled halves.

SqlData Integrity

Code

snippet
-- 一条 query 里可以放多条 RECURSIVE CTE:同时向上找汇报链、向下收全部下属
WITH RECURSIVE staff(id, name, manager_id) AS (
    VALUES
        (1, 'ceo',  NULL::int),
        (2, 'vp',   1),
        (3, 'lead', 2),
        (4, 'dev',  3),
        (5, 'qa',   3)
),
-- 向上:锚点是目标员工,递归步逐级接上一层 manager
up_chain AS (
    SELECT id, name, 0 AS hops
    FROM staff WHERE id = 4
    UNION ALL
    SELECT m.id, m.name, u.hops + 1
    FROM up_chain u JOIN staff m ON m.id = u.manager_id
),
-- 向下:锚点是上级本人,递归步收直接下属
down_tree AS (
    SELECT id, name, 0 AS depth
    FROM staff WHERE id = 3
    UNION ALL
    SELECT s.id, s.name, d.depth + 1
    FROM down_tree d JOIN staff s ON s.manager_id = d.id
)
SELECT 'up' AS direction, hops AS level, name
FROM up_chain
UNION ALL
SELECT 'down', depth, name
FROM down_tree
ORDER BY direction DESC, level, name;
-- up 块在前:dev(0) → lead(1) → vp(2) → ceo(3);down 块:lead(0) → dev/qa(1)

Inside the snippet

At its core this is a single SELECT statement against staff, up_chain and down_tree.

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

What to watch for

  • Row counts compound across 2 joins; make sure the join keys are indexed before adapting this to production data volumes.

Putting it to use

The staff table is the working surface here.

Interactive Tools for This Topic

FAQ

Which objects does the SQL touch?
`staff`, `up_chain`, `down_tree` — joined via 2 JOIN clauses.