Sub topic 3
What PRIOR refers to
This chapter assumes you can write a basic SELECT with WHERE and ORDER BY, that you understand primary and foreign keys, and that you have written a self-join on a table such as employees. It also assumes you know the DUAL table. The previous chapter introduced START WITH and CONNECT BY. This chapter explains the operator that makes CONNECT BY work: PRIOR.
The question PRIOR answers
A hierarchical query builds a tree one level at a time. Oracle first selects the root rows. Then it repeatedly looks for rows that are children of rows it already has. The CONNECT BY condition defines what "child of" means.
That condition compares two rows: a row from the previous step and a candidate row for the next step. A single column name cannot say which row it belongs to, so Oracle uses PRIOR to mark the row from the previous step.
SELECT employee_id, last_name, manager_id, LEVEL
FROM employees
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id;In PRIOR employee_id = manager_id:
PRIOR employee_idis theemployee_idof the parent row, the row Oracle already holds.manager_id(withoutPRIOR) is themanager_idof the candidate child row.
Read the condition as "a candidate row is a child if its manager_id equals the parent's employee_id". This is the same relationship as a self-join child.manager_id = parent.employee_id. The difference is that PRIOR lets one table reference play both roles.
How Oracle evaluates it
The evaluation works like a loop, and it helps to picture it this way even though Oracle's internal implementation may differ.
- Evaluate
START WITHand return the matching rows as level 1. - For each row at the current level, call it the parent. Find every row in the table where the
CONNECT BYcondition is true, withPRIORcolumns taken from the parent and the other columns taken from the candidate. - Those rows are the next level. Repeat step 2 for each of them.
- Stop when no new rows are found.
Note that step 2 scans the whole table for each parent. Only the PRIOR side is fixed by the parent. Everything else refers to the candidate.
PRIOR is a unary operator on an expression
PRIOR is not limited to a bare column. It applies to the expression that follows it. These are valid forms:
CONNECT BY PRIOR employee_id = manager_id
CONNECT BY manager_id = PRIOR employee_id
CONNECT BY PRIOR employee_id + 0 = manager_idThe first two are equivalent, because equality is symmetric. Only the position of PRIOR relative to the column names matters, not which side of the = it sits on. Writing it on the left is a convention that many people find easier to read as "parent on the left, child on the right".
Direction depends on where PRIOR sits
Moving PRIOR to the other column reverses the walk. The two queries below start from different places and use opposite conditions.
-- Top-down: children of each row are rows whose manager_id equals the parent's employee_id
SELECT employee_id, last_name, LEVEL
FROM employees
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id;-- Bottom-up: the next row is the one whose employee_id equals the parent's manager_id
SELECT employee_id, last_name, LEVEL
FROM employees
START WITH employee_id = 107
CONNECT BY employee_id = PRIOR manager_id;In the second query, PRIOR manager_id is the manager of the row Oracle already holds. The candidate is the employee whose employee_id matches that value. So each step moves from an employee to their manager. The result is employee 107, then their manager, then that manager's manager, up to the top.
A useful rule: PRIOR goes on the column that points at the next row to find, from the parent's side. The next chapters on direction return to this, so for now remember that the position of PRIOR decides whether you walk down or up.
| Condition | Parent's value used | Candidate matched on | Direction |
|---|---|---|---|
| `PRIOR employee_id = manager_id` | parent's `employee_id` | candidate's `manager_id` | down |
| `employee_id = PRIOR manager_id` | parent's `manager_id` | candidate's `employee_id` | up |
Common errors
Leaving PRIOR out
If you write CONNECT BY employee_id = manager_id, no column is tied to the parent. The condition then compares two columns of the same candidate row. For most employee data, that is true only for a row that is its own manager, so you get the root rows and little else. Oracle does not warn you. The query runs and returns an unexpected result. Always check that PRIOR appears in the condition.
A related case is the row generator in the next sections of this tutorial. There, leaving out PRIOR is deliberate, and the condition uses only LEVEL.
Putting PRIOR on both sides
SELECT employee_id
FROM employees
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = PRIOR manager_id;Here both sides come from the parent, so the candidate row is never consulted. Every candidate passes or fails together, based on the parent alone. The result is either no children or an endless expansion. In the second case, Oracle raises ORA-01436: CONNECT BY loop in user data. If you see this error, first check whether your PRIOR placement is correct, and only then suspect real cycles in the data.
Mixing up the columns
Using the wrong pair of columns gives a valid query that returns a wrong tree. Typical mistakes are joining employee_id to employee_id, or comparing manager_id to department_id. Check that the column on the PRIOR side is the key being referenced, and the other column is the foreign key that references it.
PRIOR outside the CONNECT BY clause
PRIOR is allowed in other parts of the query. It can appear in the SELECT list and in WHERE, where it returns the parent's value for the current row. This is a convenient way to show each row next to its parent:
SELECT employee_id,
last_name,
PRIOR last_name AS parent_name,
LEVEL
FROM employees
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id;For root rows, there is no parent, so PRIOR last_name is NULL. For every other row, it is the name of the row it was reached from. In a top-down query that is the manager. In a bottom-up query it is the employee one step closer to the start.
This differs from manager_id in one way. PRIOR last_name gives you columns of the parent without a self-join, so you can show the manager's name without joining back to employees.
Additional conditions with PRIOR
The CONNECT BY condition can combine several predicates. You can apply PRIOR to more than one column when a relationship needs several keys. For example, a table whose key is a pair of columns needs both in the condition:
SELECT region_id, branch_id, branch_name, LEVEL
FROM branches
START WITH parent_branch_id IS NULL
CONNECT BY PRIOR branch_id = parent_branch_id
AND PRIOR region_id = region_id;Each candidate must match the parent on both columns. Predicates that do not use PRIOR act as filters on the candidate. They cut off a branch when they fail. Chapter 8 covers that in detail.
Checking your understanding of the direction
A quick way to check your condition is to say it aloud with the word "parent". For PRIOR employee_id = manager_id: "the parent's employee id is the candidate's manager id". That sentence is true for a child. For employee_id = PRIOR manager_id: "the candidate's employee id is the parent's manager id". That sentence is true for a manager. If the sentence describes the relationship you want, the placement is right.
Exercise
Given the query below, which row does Oracle return after employee 107 at LEVEL 1, and why? Then rewrite the query so that it returns the people who report directly or indirectly to employee 107 instead. SELECT employeeid, lastname, LEVEL FROM employees START WITH employeeid = 107 CONNECT BY employeeid = PRIOR manager_id;
Show answer
The next row is employee 107's manager. PRIOR managerid is the parent's managerid (the value in the row for 107), and the candidate row is the one whose employeeid equals it. The query then continues to that manager's manager, up to the top. To walk down to everyone who reports to 107, move PRIOR to the other column: CONNECT BY PRIOR employeeid = managerid. Each candidate is then a row whose managerid equals the parent's employee_id.
Exercise
A query uses CONNECT BY employeeid = managerid with START WITH manager_id IS NULL. It returns only the top employee and no one else. Explain why, and fix it.
Show answer
There is no PRIOR, so the condition compares employeeid and managerid of the same candidate row and is not tied to the parent. It is rarely true, so no children are found and only the START WITH row appears. The fix is to add PRIOR to the key being referenced: CONNECT BY PRIOR employeeid = managerid.