Sub topic 8
WHERE versus conditions in CONNECT BY
This chapter assumes you can write a basic top-down query with START WITH, CONNECT BY PRIOR and LEVEL. The examples use the employees table from Oracle's HR sample schema. Each row has an employee_id, a manager_id, a last_name and a salary.
A hierarchical query accepts filters in two places. A condition in WHERE and a condition in CONNECT BY can look alike, but they return different rows. The difference is when each one runs.
The order of evaluation
Oracle builds the tree first and filters it afterward. For a query with a hierarchy, it works in this order:
- If the
FROMclause contains a join, Oracle evaluates the join first. This includes join conditions written inWHERE. - Oracle evaluates
START WITHandCONNECT BYto build the tree. - Oracle applies the remaining
WHEREpredicates to the rows the tree produced.
The consequence is that CONNECT BY decides which rows can be reached. WHERE can only hide rows that were already reached.
Filtering with WHERE
Suppose you want to see only employees who earn more than 5000.
SELECT employee_id, last_name, salary, LEVEL
FROM employees
WHERE salary > 5000
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id;Oracle walks the whole tree. Only afterward does it drop the rows with salary <= 5000. If a low-paid manager has a well-paid report, the report still appears. Its LEVEL is unchanged, because the level was assigned while the full tree was being built. The output can therefore skip levels. You may see a row at level 4 with no level 3 row above it in the result.
Use WHERE when you want to remove rows from the display without changing the shape of the tree.
Pruning with CONNECT BY
Now put the same condition in CONNECT BY.
SELECT employee_id, last_name, salary, LEVEL
FROM employees
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id
AND salary > 5000;Oracle now treats salary > 5000 as part of the rule for reaching a child. An employee who fails it is never connected to the parent, so Oracle never visits that employee's own reports either. The whole branch below that employee disappears, even if the people in it are well paid. This is called pruning.
In the first query, a low-paid manager disappears and the well-paid reports below them stay. In the second, both disappear.
| Condition placed in | Removes the failing row | Removes the failing row's descendants | `LEVEL` of remaining rows |
|---|---|---|---|
| `WHERE` | Yes | No | Unchanged, so levels may have gaps |
| `CONNECT BY` | Yes | Yes | Continuous from the root |
Root rows are not pruned
The CONNECT BY condition describes how a child connects to its parent. A root row has no parent, so the condition never applies to it. START WITH alone decides which rows are roots.
In the pruning query above, the top manager appears even if their salary is 4000. Only their descendants are tested against salary > 5000. If you need the root to pass the same test, repeat it in START WITH:
SELECT employee_id, last_name, salary, LEVEL
FROM employees
START WITH manager_id IS NULL AND salary > 5000
CONNECT BY PRIOR employee_id = manager_id
AND salary > 5000;Conditions that use PRIOR
In CONNECT BY, an unqualified column refers to the child row. A column prefixed with PRIOR refers to the parent row. That gives you a second kind of pruning, based on the parent.
To remove one employee and everything below them, test the child:
SELECT employee_id, last_name, LEVEL
FROM employees
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id
AND last_name <> 'Kochhar';Kochhar is excluded, and so is every report under Kochhar, because Kochhar is never connected.
To keep Kochhar on screen but hide the reports, test the parent:
SELECT employee_id, last_name, LEVEL
FROM employees
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id
AND PRIOR last_name <> 'Kochhar';Kochhar is connected to the top manager, so Kochhar appears. When Oracle looks for Kochhar's children, PRIOR last_name is 'Kochhar', the condition fails, and no children are found. The row stays and the branch below it is cut off.
Limiting depth
LEVEL is available in both clauses, so the same distinction applies to depth.
SELECT employee_id, last_name, LEVEL
FROM employees
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id
AND LEVEL <= 3;This stops traversal after the third level, so Oracle never reads deeper rows.
SELECT employee_id, last_name, LEVEL
FROM employees
WHERE LEVEL <= 3
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id;This returns the same rows. Oracle builds the entire tree first and then discards everything past level 3. On a large tree the first form does less work. Put depth limits in CONNECT BY.
Filtering on joined tables
Because a join in FROM runs first, a filter on a joined table acts before the tree is built. Consider a query that joins departments:
SELECT e.employee_id, e.last_name, d.department_name, LEVEL
FROM employees e
JOIN departments d ON d.department_id = e.department_id
WHERE d.location_id = 1700
START WITH e.manager_id IS NULL
CONNECT BY PRIOR e.employee_id = e.manager_id;Here the join comes first. If d.location_id = 1700 is written in WHERE and Oracle treats it as part of the join, employees in other locations are removed before the hierarchy is built. Their reports can then lose their parent link, and the tree breaks into pieces. Oracle's documentation says join predicates written in WHERE are evaluated before CONNECT BY. A predicate on one table in a multi-table query is not guaranteed to behave like a post-filter on the hierarchy.
Two ways to make the intent explicit:
- Build the hierarchy in an inline view that contains only
employees, then join and filter outside it. - Put the condition in
CONNECT BYif you want pruning.
Here is the first approach:
SELECT t.employee_id, t.last_name, d.department_name, t.lvl
FROM (
SELECT employee_id, last_name, department_id, LEVEL AS lvl
FROM employees
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id
) t
JOIN departments d ON d.department_id = t.department_id
WHERE d.location_id = 1700;The hierarchy is complete before the filter runs, so the filter hides rows and prunes nothing.
Choosing between them
| You want to... | Put the condition in |
|---|---|
| Hide some rows but keep their descendants | `WHERE` |
| Exclude a row and its whole subtree | `CONNECT BY`, tested on the child |
| Show a row but hide its subtree | `CONNECT BY`, tested with `PRIOR` |
| Stop at a maximum depth | `CONNECT BY` with `LEVEL` |
| Exclude a root row | `START WITH` |
Common mistakes
- Putting a business filter such as
status = 'ACTIVE'inCONNECT BYand then wondering why entire teams vanish when one manager is inactive. UseWHEREif inactive managers should be hidden but their reports kept. - Putting a depth limit in
WHEREand expecting it to speed the query up. It does not, because the full tree is still built. - Expecting the
CONNECT BYcondition to remove a root row. OnlySTART WITHcontrols roots. - Forgetting that
LEVELis assigned beforeWHEREruns, so filtered output can show gaps in levels.
Exercise
A manager with employeeid 120 earns 4000. All of that manager's reports earn 8000. You run a top-down query from the top manager. Query A uses WHERE salary > 5000. Query B uses CONNECT BY PRIOR employeeid = manager_id AND salary > 5000. Which query returns the reports of employee 120, and why?
Show answer
Query A returns them. WHERE runs after the tree is built, so it removes only employee 120 and leaves the reports in the output. Query B does not return them, because employee 120 fails the condition in CONNECT BY, is never connected to the parent, and so Oracle never reaches the reports below.
Exercise
Write a CONNECT BY condition that shows employee 101 in the output but returns none of 101's direct or indirect reports.
Show answer
Test the parent row with PRIOR: CONNECT BY PRIOR employeeid = managerid AND PRIOR employeeid <> 101. Employee 101 is connected to the manager above, so the row appears. When Oracle looks for the children of 101, PRIOR employeeid equals 101, the condition fails, and the subtree is cut off.