Recursive CTE Subtree Salary Rollup

Carry (root, member) pairs through a recursive CTE and aggregate outside it, because Postgres rejects aggregates over the recursive reference.

SqlData Integrity

Code

snippet
-- subtree salary rollup in a recursive CTE: SUM must sit outside the recursive term
-- Postgres rejects aggregation over the recursive reference, so recursion only expands (root, member) pairs
CREATE TABLE employees (
    employee_id int PRIMARY KEY,
    manager_id  int REFERENCES employees(employee_id),
    name        text NOT NULL,
    salary      int  NOT NULL
);

INSERT INTO employees VALUES
    (1, NULL, 'ceo',  5000),
    (2, 1,    'cto',  4000),
    (3, 2,    'dev1', 3000),
    (4, 2,    'dev2', 3000),
    (5, 1,    'coo',  3800);

WITH RECURSIVE subtree AS (
    -- anchor: every employee is a member of their own subtree
    SELECT employee_id AS root_id, employee_id, salary
    FROM employees

    UNION ALL

    SELECT s.root_id, e.employee_id, e.salary
    FROM employees e
    JOIN subtree s ON e.manager_id = s.employee_id
)
SELECT
    m.employee_id,
    m.name,
    SUM(s.salary) AS subtree_salary   -- includes the employee plus every direct and indirect report
FROM employees m
JOIN subtree s ON s.root_id = m.employee_id
GROUP BY m.employee_id, m.name
ORDER BY subtree_salary DESC;

What the code does

SELECT / INSERT / CREATE statements share the script, touching employees and subtree.

Mechanically, the statements are built from: a CTE (WITH … AS) that names an intermediate result before the main query; 2 JOINs combining rows across tables; SUM aggregation; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order; a UNION merging rows produced by different queries; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; a foreign-key REFERENCES guard tying rows to the parent table.

Points of care

  • 2 joins multiply the intermediate row count; index the join keys before running this shape against full-size tables.

Applying it

The employees table is the working surface here.

Statements that matter

CREATE TABLE employees (
    employee_id int PRIMARY KEY,
    manager_id  int REFERENCES employees(employee_id),
    name        text NOT NULL,
    salary      int  NOT NULL
);
INSERT INTO employees VALUES
    (1, NULL, 'ceo',  5000),
    (2, 1,    'cto',  4000),
    (3, 2,    'dev1', 3000),
    (4, 2,    'dev2', 3000),
    (5, 1,    'coo',  3800);

Interactive Tools for This Topic

FAQ

Which relations are involved here?
The references are `employees`, `subtree`, with 2 joins tying them together.