Sub topic 12
Counting and summing over subtrees
Assume you know basic SELECT, GROUP BY, and self-joins, and that employees has an employee_id primary key, a manager_id parent key, and a numeric salary. A subtree contains a row and all of its descendants.
A hierarchical query first expands the employee relationships. SQL aggregation then operates on the expanded rows. Therefore, COUNT(*) counts rows in a generated subtree, and SUM(salary) adds the salaries of those rows.
SELECT COUNT(*) AS subtree_rows,
SUM(salary) AS subtree_salary
FROM employees
START WITH employee_id = 100
CONNECT BY PRIOR employee_id = manager_id;This query creates one subtree rooted at employee 100. The count includes employee 100 itself. The salary total also includes the root employee's salary.
| Expression | Meaning |
|---|---|
| `COUNT(*)` | Number of rows in the subtree, including its root |
| `COUNT(*) - 1` | Number of descendants below the root |
| `SUM(salary)` | Salary total for the root and all descendants |
To calculate results for every employee, omit START WITH. Oracle treats every row as a root and generates that row's descendants.
SELECT CONNECT_BY_ROOT employee_id AS root_employee_id,
COUNT(*) AS subtree_size,
SUM(salary) AS subtree_salary,
COUNT(*) - 1 AS total_reports
FROM employees
CONNECT BY PRIOR employee_id = manager_id
GROUP BY CONNECT_BY_ROOT employee_id
ORDER BY root_employee_id;CONNECT_BY_ROOT employee_id identifies the root for each generated row. The GROUP BY gathers all rows belonging to the same root. For example, the group for manager 100 contains employee 100, direct reports, and reports at every lower level.
The total_reports expression excludes the root from the count. If you need the salary of descendants only, subtract the root salary from the subtree total. One way is to calculate the root salary in a separate query and join it to the aggregate:
WITH subtree_totals AS (
SELECT CONNECT_BY_ROOT employee_id AS root_employee_id,
COUNT(*) AS subtree_size,
SUM(salary) AS subtree_salary
FROM employees
CONNECT BY PRIOR employee_id = manager_id
GROUP BY CONNECT_BY_ROOT employee_id
)
SELECT s.root_employee_id,
s.subtree_size - 1 AS total_reports,
s.subtree_salary - r.salary AS reports_salary
FROM subtree_totals s
JOIN employees r
ON r.employee_id = s.root_employee_id
ORDER BY s.root_employee_id;This query returns one row per employee. reports_salary excludes the manager's own salary but includes every descendant's salary.
Be careful with the no-START WITH form. It intentionally generates many overlapping subtrees. A large hierarchy can produce far more rows than the base table, because one employee may appear in the subtree for their manager, their manager's manager, and so on.
Exercise
In the grouped query, why does COUNT(*) - 1 represent the number of reports rather than the number of rows in the subtree?
Show answer
Each generated subtree includes its root. Subtracting one removes that root and leaves only its descendants.