Sub topic 8
WHERE versus conditions in CONNECT BY
Prerequisites and the working model
This chapter assumes that you know basic SELECT, WHERE, and ORDER BY, understand primary and foreign keys, and can write a self-join. The examples use an employees table:
employee_ididentifies an employee.manager_idstores that employee's manager.salarystores the employee's salary.
A hierarchical query first chooses root rows with START WITH. It then uses CONNECT BY to find each row's children. Finally, a WHERE clause filters rows from the result.
Filtering rows with WHERE
A WHERE condition removes matching rows from the final result. It does not change how Oracle finds descendants.
SELECT employee_id, last_name, manager_id, LEVEL
FROM employees
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id
WHERE salary > 5000;Oracle still traverses every branch from every root. After traversal, it returns only employees whose salary is greater than 5000.
This can produce a surprising result. A manager with a salary of 4000 disappears, but a qualifying employee below that manager can still appear. The child keeps its position in the hierarchy even though its parent is absent from the displayed result.
Pruning branches with CONNECT BY
Put a condition in CONNECT BY when a row must qualify before Oracle can continue through it.
SELECT employee_id, last_name, manager_id, LEVEL
FROM employees
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id
AND salary > 5000;Here, Oracle can add a child only when the child has a salary greater than 5000. If a child fails the condition, Oracle does not traverse that child's descendants. This is branch pruning.
The root condition still comes from START WITH. Therefore, a root with a salary of 5000 or less can remain in the output unless the salary test is also added to START WITH.
SELECT employee_id, last_name, manager_id, LEVEL
FROM employees
START WITH manager_id IS NULL
AND salary > 5000
CONNECT BY PRIOR employee_id = manager_id
AND salary > 5000;This version requires qualifying roots and qualifying descendants.
Common errors
| Requirement | Place the condition | Effect |
|---|---|---|
| Display only expensive employees | `WHERE` | Traverses all branches, then hides low-salary rows |
| Do not enter a low-salary employee's branch | `CONNECT BY` | Excludes that child and prevents traversal below it |
| Allow only expensive roots | `START WITH` | Chooses expensive roots only |
Do not assume that WHERE preserves a visually connected tree. It filters rows after the hierarchy has been built. Use CONNECT BY when the business rule says that an unacceptable employee blocks access to the employees below them.
Exercise
You need to list all employees under the company roots, but hide employees whose salary is 5000 or less. Should the salary condition go in WHERE or CONNECT BY?
Show answer
Put it in WHERE. The requirement hides rows but does not say that a low-salary employee should block traversal to descendants.