Sub topic 7
Walking up the tree: bottom-up queries
This chapter covers reversing the direction of a hierarchical query so it starts at a row and climbs through its ancestors. It assumes you can write a top-down query with START WITH and CONNECT BY PRIOR, and that you know what LEVEL returns. The examples use the employees table, where manager_id refers to employee_id in the same table.
Direction comes from where PRIOR sits
In a top-down query you write CONNECT BY PRIOR employee_id = manager_id. Oracle reads this as follows. For each parent row already in the result, find the rows whose manager_id equals the parent's employee_id. Those rows are the children.
PRIOR marks which side of the comparison is taken from the parent row. The other side is taken from the candidate child row. Moving PRIOR to the other column reverses the walk:
| Condition | Parent value used | Candidate child matches on | Direction |
|---|---|---|---|
| `PRIOR employee_id = manager_id` | parent's `employee_id` | child's `manager_id` | Down, to direct reports |
| `employee_id = PRIOR manager_id` | parent's `manager_id` | child's `employee_id` | Up, to the manager |
In the second form, the "child" Oracle looks for is the row whose own employee_id equals the current row's manager_id. That row is the current row's manager. So each step moves one level up the organization.
A bottom-up query
This query starts at employee 107 and returns that employee followed by each manager above them.
SELECT employee_id, last_name, LEVEL
FROM employees
START WITH employee_id = 107
CONNECT BY employee_id = PRIOR manager_id;Two things changed from the top-down version:
START WITHnow names a specific row instead of the row with no manager. The start row is the leaf end of the path, so you choose it with a condition that identifies the employee you care about.PRIORis attached tomanager_id.
Each row's LEVEL is its distance from the start row, counted from 1. Employee 107 has LEVEL 1, their manager has LEVEL 2, and so on. The top manager has the highest LEVEL, not the lowest. This is the reverse of what you get in a top-down query, so any code that relies on LEVEL = 1 meaning "the CEO" needs rethinking.
The walk ends on its own. The top manager has a NULL manager_id, and employee_id = NULL is never true, so no further row matches.
Each bottom-up step finds at most one row, because employee_id is unique. A bottom-up query therefore returns a single chain, not a tree. That is one reason it is usually cheap to run.
Why the output order looks upside down
Without an ORDER BY, Oracle returns hierarchical rows in the order it visits them. For a bottom-up query, that is the start row first, then its manager, and so on to the top. Here that reads from the employee to the CEO.
If you want the display to read from the top down, sort by LEVEL descending:
SELECT employee_id, last_name, LEVEL
FROM employees
START WITH employee_id = 107
CONNECT BY employee_id = PRIOR manager_id
ORDER BY LEVEL DESC;An ordinary ORDER BY replaces the hierarchical order, which is fine here because the result is a single chain with one row per level.
Reading the chain as one string
A common use of a bottom-up query is to show an employee's management chain. You can combine SYS_CONNECT_BY_PATH with the reversed condition, which is covered in detail in a later chapter. This sketch shows the idea:
SELECT SYS_CONNECT_BY_PATH(last_name, ' < ') AS chain
FROM employees
WHERE manager_id IS NULL
START WITH employee_id = 107
CONNECT BY employee_id = PRIOR manager_id;The WHERE clause keeps only the top manager's row. Because the path is built as the walk proceeds, that row carries the whole chain from employee 107 up to the top. The result is one row.
Starting from many rows
START WITH can match more than one row. Oracle then runs one walk per start row and returns all of them in a single result set. This query climbs from every employee in department 60:
SELECT employee_id, last_name, manager_id, LEVEL
FROM employees
START WITH department_id = 60
CONNECT BY employee_id = PRIOR manager_id;Shared managers appear more than once, once for each walk that reaches them. If five employees report to the same manager, that manager appears five times, each with its own LEVEL value relative to the start row it came from. This is correct behavior, but it surprises people who expect a distinct list of managers.
To get a distinct list, select the columns you need and apply DISTINCT:
SELECT DISTINCT employee_id, last_name
FROM employees
START WITH department_id = 60
CONNECT BY employee_id = PRIOR manager_id;Do not include LEVEL in a DISTINCT list here. The same manager can appear at different levels in different walks, and then DISTINCT will not collapse the rows.
Choosing the start row
The start condition is the part of a bottom-up query that changes between uses, so it deserves care:
- Use a primary key or other unique column when you want one chain.
START WITH employee_id = 107returns exactly one walk. - Use a non-unique column such as a department or a job when you want several walks, and expect repeated ancestors.
- If
START WITHmatches no rows, the query returns no rows and raises no error. A misspelled value gives an empty result. - A bind variable works well:
START WITH employee_id = :emp_id. This lets the same statement serve any employee.
Common mistakes
- Putting
PRIORon the wrong side. If you writeSTART WITH employee_id = 107withCONNECT BY PRIOR employee_id = manager_id, you get employee 107 and everyone below them, which is a top-down walk from the middle of the tree. The query runs without error, so the mistake is easy to miss. Check the direction by looking at which columnPRIORtouches. - Assuming
LEVEL = 1is the root. In a bottom-up query,LEVEL = 1is the start row. - Expecting a tree. A bottom-up walk from one row is a chain. If you see branching, the start condition matched several rows.
- Forgetting that
NULLends the walk. If the data uses a sentinel such as0or the row's own id for "no manager" instead ofNULL, the walk never ends on its own. Oracle then reports a loop in the user data, which is the cycle problem covered in a later chapter.
When to prefer each direction
| Question | Direction | Typical `START WITH` |
|---|---|---|
| Who reports to this manager, directly or indirectly? | Top-down | The manager's row |
| Show the whole organization | Top-down | `manager_id IS NULL` |
| Who is above this employee? | Bottom-up | The employee's row |
| Does employee A sit under employee B? | Either | See the exercise below |
The last row can be answered in either direction. Walking up from A and checking whether B appears reads naturally, and it touches fewer rows than walking down from B in a large organization.
Exercise
Write a query that returns only the manager chain above employee 107, excluding employee 107 themselves, ordered from the direct manager up to the top.
Show answer
SELECT employeeid, lastname, LEVEL FROM employees WHERE LEVEL > 1 START WITH employeeid = 107 CONNECT BY employeeid = PRIOR manager_id ORDER BY LEVEL; The WHERE clause removes the start row (LEVEL 1) after the walk is finished, so the ancestors are still reached. Sorting by LEVEL ascending lists the direct manager first and the top manager last.
Exercise
A query uses START WITH departmentid = 60 and CONNECT BY employeeid = PRIOR manager_id. The CEO appears six times in the result. Why, and how do you list each manager only once?
Show answer
Six employees in department 60 are start rows, and each walk climbs to the CEO, so the CEO is returned once per walk. Select only the identifying columns and use SELECT DISTINCT, leaving LEVEL out of the select list because the CEO has a different LEVEL in walks of different lengths.