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.
Code
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
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.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.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.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- What relations does the SQL touch?
- The references are `employees`, `ancestors`, with one join tying the pair together.
Report a problem with this exampleOpens a pre-filled issue on GitHub.