Sub topic 12
Counting and summing over subtrees
This chapter assumes you can write a basic START WITH ... CONNECT BY PRIOR query. It also assumes you know LEVEL and CONNECT_BY_ROOT, and standard GROUP BY aggregation. The examples use the employees table, where manager_id points back to employee_id.
Why aggregation over a hierarchy is different
A normal GROUP BY collapses rows that share a column value. A manager's team does not share a column value. It is a set of rows reachable from that manager through the tree. To count or sum a team, you need each row labeled with the ancestor it belongs under, and then you group by that label.
CONNECT_BY_ROOT provides the label. A hierarchical query that has no START WITH treats every row as a starting point. Each employee therefore produces their own subtree in the result. Every row of that subtree carries the starting employee as its root. Grouping by the root gives one group per subtree.
Counting every employee's subtree
SELECT CONNECT_BY_ROOT employee_id AS manager_id,
COUNT(*) - 1 AS total_reports
FROM employees
CONNECT BY PRIOR employee_id = manager_id
GROUP BY CONNECT_BY_ROOT employee_id;Each group contains the root row plus all of its descendants. COUNT(*) counts the root too, so you subtract one. An employee with no reports forms a group of one row and gets 0.
The result table has one row per employee, so you can join it back to employees to show names.
Summing a measure over a subtree
Any aggregate works the same way. This query computes headcount and total salary for each subtree and joins the result to the table for names.
SELECT m.employee_id,
m.last_name,
t.headcount,
t.payroll
FROM employees m
JOIN (SELECT CONNECT_BY_ROOT employee_id AS root_id,
COUNT(*) - 1 AS headcount,
SUM(salary) AS payroll
FROM employees
CONNECT BY PRIOR employee_id = manager_id
GROUP BY CONNECT_BY_ROOT employee_id) t
ON t.root_id = m.employee_id
WHERE t.headcount > 0
ORDER BY t.payroll DESC;SUM(salary) includes the root's own salary. If you want only the reports' salaries, exclude the root row with a conditional aggregate:
SELECT CONNECT_BY_ROOT employee_id AS manager_id,
COUNT(CASE WHEN LEVEL > 1 THEN 1 END) AS total_reports,
SUM(CASE WHEN LEVEL > 1 THEN salary END) AS reports_payroll
FROM employees
CONNECT BY PRIOR employee_id = manager_id
GROUP BY CONNECT_BY_ROOT employee_id;The root row is the only row in each group where LEVEL = 1. So LEVEL > 1 selects the descendants. This form avoids the - 1 adjustment, and it handles sums where subtracting the root's value would be awkward.
Aggregating one subtree
You often need a single answer, such as the size of one manager's organization. Add START WITH to restrict the roots, then aggregate without grouping:
SELECT COUNT(*) - 1 AS total_reports,
SUM(salary) AS payroll_including_manager
FROM employees
START WITH employee_id = 101
CONNECT BY PRIOR employee_id = manager_id;This is cheaper than the all-roots form because Oracle walks only one subtree.
Aggregating by level
LEVEL can be a grouping key, which shows the shape of the tree:
SELECT LEVEL AS depth,
COUNT(*) AS employees_at_depth,
AVG(salary) AS avg_salary
FROM employees
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id
GROUP BY LEVEL
ORDER BY LEVEL;Here the single START WITH root means the groups describe the whole tree from the top. Use it to find how wide each layer is or how deep the organization goes (MAX(LEVEL)).
What the cost looks like
When there is no START WITH, Oracle expands every row into its full subtree before grouping. The number of intermediate rows is the sum of all subtree sizes. That equals the sum of every row's depth, since each row appears once under each of its ancestors and once under itself.
| Tree shape | Rows produced before grouping |
|---|---|
| Flat (everyone reports to one root) | About 2 × N |
| Balanced, depth d | About N × d |
| A single chain of N employees | About N × (N + 1) / 2 |
For a typical organization of a few thousand people with depth under ten, this is small. For a deep chain, such as a long bill-of-materials or a threaded comment table, it grows quadratically. If you need the numbers for only a few roots, restrict them. Put a filter in START WITH rather than filtering afterward in an outer query.
Gotchas
Restrictions on CONNECT_BY_ROOT
CONNECT_BY_ROOT is allowed in the select list, WHERE, ORDER BY and GROUP BY. It cannot appear in the START WITH or CONNECT BY conditions. If you need to compare a row against its root while walking the tree, you cannot do it inside CONNECT BY. Instead, carry the value forward with SYS_CONNECT_BY_PATH or switch to recursive WITH.
Duplicate paths inflate counts
Aggregation assumes a real tree, where each row has at most one parent. If the data allows a row to be reachable through two different paths (for example, a part used in two assemblies, or an employee with two managers recorded), the row appears once per path. COUNT(*) then counts it more than once. To count each distinct descendant once, use COUNT(DISTINCT employee_id). To sum without duplicates you need a different approach, because SUM(DISTINCT salary) removes equal salaries rather than duplicate rows.
Cycles stop the query
Aggregates over a cyclic hierarchy fail with ORA-01436: CONNECT BY loop in user data. Add NOCYCLE after CONNECT BY to let the query finish. When you do, rows are still counted once per path up to the point where the cycle would repeat, so treat the totals as suspect and fix the data.
SELECT CONNECT_BY_ROOT employee_id AS manager_id,
COUNT(*) - 1 AS total_reports
FROM employees
CONNECT BY NOCYCLE PRIOR employee_id = manager_id
GROUP BY CONNECT_BY_ROOT employee_id;Pruning changes what you count
A condition inside CONNECT BY, such as AND salary > 5000, removes a row and everything below it. The counts then describe only the surviving branches. A WHERE condition removes rows after the walk, so descendants of a removed row still appear and are still counted. Decide which behavior the question requires. "How many people with salary over 5000 report to this manager?" is a WHERE question. "How big is the part of the organization reachable through well-paid people?" is a pruning question.
Mixing aggregates and ORDER SIBLINGS BY
ORDER SIBLINGS BY orders rows within the hierarchy. It cannot be used together with GROUP BY, because grouping destroys the row-by-row tree order. Use an ordinary ORDER BY on the aggregate or on the root.
Alternative: a scalar subquery per row
If you need the subtree count as one more column in a tree display, a correlated scalar subquery works:
SELECT e.employee_id,
e.last_name,
(SELECT COUNT(*) - 1
FROM employees
START WITH employee_id = e.employee_id
CONNECT BY PRIOR employee_id = manager_id) AS total_reports
FROM employees e;It is easy to read and each subtree walk can use the index on manager_id. However, it runs one hierarchical query per outer row. The grouped form does the same work in a single statement and is usually the better choice when you need all rows.
Exercise
Write a query that returns, for each manager who has at least one report, the manager's employee_id and the number of people anywhere below them whose salary is above 8000. The manager's own salary must not be counted.
Show answer
SELECT CONNECTBYROOT employeeid AS managerid,
COUNT(CASE WHEN LEVEL > 1 AND salary > 8000 THEN 1 END) AS highpaidreports
FROM employees
CONNECT BY PRIOR employeeid = managerid
GROUP BY CONNECTBYROOT employee_id
HAVING COUNT() > 1;
The LEVEL > 1 test removes the root row from the count. `HAVING COUNT() > 1 keeps only roots whose group has more than one row, which means they have at least one report. The salary test sits in the aggregate rather than in CONNECT BY` so that low-paid employees still connect their own reports to the tree.
Exercise
A colleague runs the all-roots counting query on a table of 50,000 rows and it is slow, but they only need the counts for the five vice presidents. What should they change?
Show answer
Add a START WITH that selects only those five employees, for example START WITH employeeid IN (101, 102, 103, 104, 105), and keep GROUP BY CONNECTBYROOT employeeid. Oracle then expands only five subtrees instead of one per row. Filtering the finished result with an outer WHERE does not help, because the full expansion happens first.