Sub topic 15
Performance and indexing considerations
This chapter assumes you can write a top-down and bottom-up CONNECT BY query. It also assumes you can read an Oracle execution plan at a basic level (EXPLAIN PLAN and DBMS_XPLAN). It explains where the cost of a hierarchical query comes from and which indexes and query shapes keep it small.
How Oracle walks the tree
A CONNECT BY query does not join the whole table to itself. It starts from the rows selected by START WITH. For each row it finds the children that satisfy the CONNECT BY condition, then repeats for those children until no more rows qualify.
Each step is a lookup. In a top-down query (PRIOR employee_id = manager_id), Oracle holds a parent's employee_id and needs every row whose manager_id equals it. Without a suitable access path, each lookup scans the whole table.
The number of lookups equals the number of rows visited. A table of 100,000 employees without an index on manager_id can mean 100,000 full scans. That cost grows with the square of the table size, which is why an unindexed hierarchy query that is fine on a test table can stall in production.
Index the join column
For top-down queries, index the child-side column, which is manager_id here.
CREATE INDEX emp_manager_ix ON employees (manager_id);The Oracle HR sample schema already ships with an index of this kind. If you get ORA-00955, an index with that name exists and you can skip this step.
For bottom-up queries (CONNECT BY employee_id = PRIOR manager_id), each step looks up a row by employee_id. The primary key index already serves this. Bottom-up queries are cheap: they touch one row per level, so a query that returns the ancestors of one employee reads a handful of rows.
| Query shape | Lookup column per step | Index that helps |
|---|---|---|
| Top-down: `PRIOR employee_id = manager_id` | `manager_id` | Index on `manager_id` |
| Bottom-up: `employee_id = PRIOR manager_id` | `employee_id` | Primary key on `employee_id` |
| `START WITH employee_id = 107` | `employee_id` | Primary key |
| `START WITH manager_id IS NULL` | `manager_id` | Usually none (see below) |
START WITH and NULL
A B-tree index does not store entries where every indexed column is NULL. So START WITH manager_id IS NULL cannot use emp_manager_ix, and Oracle scans the table once to find the roots. This happens once per query, so it is rarely the problem. The repeated child lookups are what matter. If the root lookup does matter, start from a known key instead, for example START WITH employee_id = 100.
Check the plan
Run EXPLAIN PLAN and look at the hierarchical operation and the access paths beneath it.
EXPLAIN PLAN FOR
SELECT employee_id, last_name, LEVEL
FROM employees
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id;
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);You will see an operation named CONNECT BY WITH FILTERING or CONNECT BY WITHOUT FILTERING. The second form is usually used when the optimizer can read the table once and build the hierarchy in memory. The first form drives repeated lookups, which is where an index on manager_id appears as an INDEX RANGE SCAN in the second branch. The exact plan depends on your version, statistics, and data volume, so compare plans on realistic data rather than on a ten-row table.
The estimated plan can mislead. To see the rows actually processed, run the query with a statistics hint and read the cursor plan:
SELECT /*+ GATHER_PLAN_STATISTICS */ employee_id, last_name, LEVEL
FROM employees
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id;
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY_CURSOR(format => 'ALLSTATS LAST'));Compare E-Rows (estimated) with A-Rows (actual). A large gap suggests stale statistics. Refresh them with DBMS_STATS.GATHER_TABLE_STATS if so.
Prune early, not late
A WHERE condition on a hierarchical query removes rows after the tree is built. The branches below a rejected row were still traversed. A condition in CONNECT BY stops the traversal at that row, so those branches are never visited.
Compare these two queries:
-- Traverses the full tree, then discards rows
SELECT employee_id, last_name, LEVEL
FROM employees
WHERE salary > 5000
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id;
-- Stops at any employee with salary <= 5000
SELECT employee_id, last_name, LEVEL
FROM employees
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id
AND salary > 5000;They return different results, because pruning also removes everything below a failing employee. Choose by meaning first. When pruning is the meaning you want, it is also the cheaper query. You can also limit depth with a condition such as AND LEVEL <= 3, which stops the walk after three levels.
Limit the number of roots
If you omit START WITH, every row is a root, and Oracle walks a subtree from each one. The total rows processed equals the sum of all subtree sizes, which is the sum of every row's depth. For the deep tree of a large company this can be many times the table size.
The "total reports per manager" pattern from the aggregation chapter has this cost:
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;It is convenient and fine for thousands of rows. For a large table, you have two options:
- Restrict the roots with
START WITHwhen you need only some managers, for exampleSTART WITH employee_id IN (100, 101). - Compute the answer once and store it, if many users ask for it repeatedly (a materialized view or a summary table).
Costs of other hierarchical features
Some features add work on top of the traversal.
ORDER SIBLINGS BYsorts the children of each parent. This is cheap per branch but adds up with wide trees. A normalORDER BYwould break the hierarchy order and sort the whole result, so useORDER SIBLINGS BYwhen you need the tree shape.NOCYCLEmakes Oracle check each new row against its ancestors. The check is a small per-row cost. Use it when the data may contain loops. If your data cannot have loops, a normal query is simpler and a loop shows up as an error you can fix.SYS_CONNECT_BY_PATHbuilds a string for every row, which grows with depth. The result is limited to 4000 bytes in a SQL string context. A long path raisesORA-01489, so use short column values, or return the path only for the rows you need.CONNECT_BY_ROOT,CONNECT_BY_ISLEAF, andLEVELare cheap. Oracle already tracks them while it traverses.
Row generation can use a lot of memory
CONNECT BY LEVEL <= N on DUAL has no table to look up and needs no index. Its cost is the number of rows requested, and the rows are produced in memory.
SELECT LEVEL AS n
FROM dual
CONNECT BY LEVEL <= 10;Ten rows are free. Ten million rows can use a lot of memory and may fail with an out-of-memory error such as ORA-30009. If you need a large number series, prefer a physical numbers table, or limit the range in the query that needs it.
Be careful when you apply CONNECT BY LEVEL to a table with more than one row. Without PRIOR, each row connects to every row, and the result grows exponentially with the number of levels. A common fix is to use DUAL, or to add a condition that ties each level to one row.
When to compare with recursive WITH
Recursive subquery factoring (WITH ... UNION ALL) follows the standard form and gives you explicit control over each step. In some versions and data sets, the optimizer picks a different plan for it. Neither form is always faster. If a CONNECT BY query is slow and the index is in place, rewrite it as a recursive WITH and compare A-Rows, buffer gets, and elapsed time using DISPLAY_CURSOR. Keep the form that is faster on your data. Do not switch on general advice alone.
A tuning checklist
- Confirm there is an index on the child column (
manager_id) for top-down queries. - Use a selective
START WITH. Avoid leaving it out. - Put filter conditions that should stop a branch in
CONNECT BY, and cap depth withLEVELwhere the question allows it. - Check statistics are current, then compare
E-RowsandA-Rows. - Remove features you do not need (
ORDER SIBLINGS BY, long paths). - For repeated whole-tree reports, store the result instead of recomputing it.
Exercise
A top-down query with START WITH managerid IS NULL and CONNECT BY PRIOR employeeid = manager_id runs on a 2-million-row employees table and takes minutes. The plan shows a full table scan on EMPLOYEES inside the CONNECT BY operation. What index do you add, and why does the START WITH clause not need it?
Show answer
Add an index on managerid, for example CREATE INDEX empmanagerix ON employees (managerid). Each step of a top-down traversal looks up the children of a parent by managerid, and without the index each lookup scans the table. START WITH managerid IS NULL does not benefit, because a B-tree index does not store entries where all indexed columns are NULL. The root lookup runs once per query, so the repeated child lookups are what the index fixes.
Exercise
You want to list only employees with salary above 5000 and everyone below them, skipping any branch whose head earns 5000 or less. Should the salary test go in WHERE or in CONNECT BY, and which is cheaper?
Show answer
Put it in CONNECT BY (AND salary > 5000). It prunes the branch, so the rows below a failing employee are never visited, which is also less work. A WHERE condition would walk the whole tree and then remove only the failing rows, and it would still return their descendants who pass.