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.
Code
-- 一条 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
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.GraphQL Query FormatterPretty-print a GraphQL query by indenting selection sets by brace depth and normalizing punctuation spacing.
FAQ
- Which objects does the SQL touch?
- `staff`, `up_chain`, `down_tree` — joined via 2 JOIN clauses.
Report a problem with this exampleOpens a pre-filled issue on GitHub.