Sub topic 7
Walking Up the Tree: Bottom-Up Queries
Assume you know basic SELECT, WHERE, and ORDER BY, primary and foreign keys, self-joins, and Oracle’s DUAL table. This chapter uses an employees table where employee_id is the primary key and manager_id stores another employee’s ID.
A self-referencing table stores a parent-child relationship in one table:
| employee_id | last_name | manager_id |
|---|---|---|
| 107 | Smith | 100 |
| 100 | King | 90 |
| 90 | Green | null |
Smith reports to King, and King reports to Green. To find Smith’s management chain, start at Smith and repeatedly move from an employee to that employee’s manager.
Reversing the traversal direction
A top-down query commonly matches a parent employee to a child employee:
CONNECT BY PRIOR employee_id = manager_idFor a bottom-up query, reverse the relationship:
SELECT employee_id, last_name, manager_id, LEVEL
FROM employees
START WITH employee_id = 107
CONNECT BY employee_id = PRIOR manager_id;START WITH chooses the row where the walk begins. In this example, employee 107 is the starting row.
The CONNECT BY condition compares each candidate row with the row found in the previous step. PRIOR manager_id means “the manager ID from the previous row.” Oracle then finds the row whose current employee_id equals that manager ID.
The result might look like this:
| employee_id | last_name | manager_id | LEVEL |
|---|---|---|---|
| 107 | Smith | 100 | 1 |
| 100 | King | 90 | 2 |
| 90 | Green | null | 3 |
LEVEL is 1 for the starting employee. Each manager above that employee increases the level by one. The walk stops when the current row has no manager or when no matching employee exists.
Understanding `PRIOR`
PRIOR identifies a value from the row already reached. Its position affects the direction of the relationship.
| Condition | Typical direction |
|---|---|
| `PRIOR employee_id = manager_id` | Manager to employees |
| `employee_id = PRIOR manager_id` | Employee to managers |
The query can begin with more than one employee:
SELECT employee_id, last_name, LEVEL
FROM employees
START WITH employee_id IN (107, 108)
CONNECT BY employee_id = PRIOR manager_id;Oracle creates a separate ancestor path for each starting row. If you need to label each path’s original employee, CONNECT_BY_ROOT employee_id preserves the root value for every returned row.
A missing manager row ends the chain early. A cycle can prevent normal completion, so use NOCYCLE when the data may contain invalid loops:
SELECT employee_id,
last_name,
LEVEL,
CONNECT_BY_ISCYCLE AS is_cycle
FROM employees
START WITH employee_id = 107
CONNECT BY NOCYCLE employee_id = PRIOR manager_id;CONNECT_BY_ISCYCLE marks a row involved in a detected cycle. It helps you identify bad organizational data without raising the usual cycle error.
Exercise
Which CONNECT BY condition walks from employee 107 to that employee’s managers?
Show answer
CONNECT BY employee_id = PRIOR manager_id