Recursive CTE Org Chart Hierarchy
Walk employee hierarchies with a recursive CTE, tracking depth and reporting paths while avoiding cycles in malformed data.
Code
-- 递归展开管理链:从 CEO 到每层汇报关系
WITH RECURSIVE org_tree AS (
SELECT
employee_id,
manager_id,
name,
1 AS depth,
ARRAY[employee_id] AS report_path,
name::text AS chain
FROM employees
WHERE manager_id IS NULL -- 锚点:顶层节点
UNION ALL
SELECT
e.employee_id,
e.manager_id,
e.name,
t.depth + 1,
t.report_path || e.employee_id,
t.chain || ' > ' || e.name
FROM employees e
JOIN org_tree t ON e.manager_id = t.employee_id
WHERE NOT t.report_path @> ARRAY[e.employee_id] -- 防环
)
SELECT
name,
depth,
chain
FROM org_tree
ORDER BY report_path;
-- 反向查询:某人的全部下属(子树)
WITH RECURSIVE subtree AS (
SELECT employee_id, name, 1 AS depth
FROM employees WHERE employee_id = 7
UNION ALL
SELECT e.employee_id, e.name, s.depth + 1
FROM employees e JOIN subtree s ON e.manager_id = s.employee_id
)
SELECT count(*) AS total_reports,
max(depth) AS max_depth
FROM subtree;What the code does
Several statements share this file — SELECT, with employees, org_tree and subtree among the objects involved.
What the statements actually assemble: a CTE (WITH … AS) that names an intermediate result before the main query; 2 JOINs combining rows across tables; a WHERE clause limiting the rows one statement is allowed to reach; COUNT, MAX aggregation; an ORDER BY that fixes the output order; a UNION folding the result sets of separate queries together.
Points of care
- 2 joins multiply the intermediate row count; confirm the join keys are indexed before pointing this at production-sized tables.
Applying it
The employees table is the working surface here.
Statements that matter
WITH RECURSIVE subtree AS (
SELECT employee_id, name, 1 AS depth
FROM employees WHERE employee_id = 7
UNION ALL
SELECT e.employee_id, e.name, s.depth + 1
FROM employees e JOIN subtree s ON e.manager_id = s.employee_id
)
SELECT count(*) AS total_reports,
max(depth) AS max_depth
FROM subtree;
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
- Which tables appear in this script?
- `employees`, `org_tree`, `subtree` — joined via 2 JOIN clauses.
Report a problem with this exampleOpens a pre-filled issue on GitHub.