Sub topic 2
START WITH and CONNECT BY: your first hierarchical query
This chapter assumes you can write basic SELECT, WHERE and ORDER BY statements, and that you understand primary and foreign keys. It also assumes you have written a self-join and know the DUAL table. The examples use the employees table from Oracle's HR sample schema. Each row has an employee_id, a last_name and a manager_id. The manager_id column points back to another row in the same table, and the top employee has NULL there.
The problem a self-join cannot solve
A self-join follows one parent-child link per join. To list an employee, their manager and their manager's manager, you write two joins. To list everyone under the top executive, you would need as many joins as the tree is deep, and you rarely know that depth in advance.
Oracle solves this with the hierarchical query clause. You describe two things, and Oracle repeats the join for you until no more rows qualify:
- Where to begin. This is the
START WITHcondition. - How one row leads to the next. This is the
CONNECT BYcondition.
Your first hierarchical query
SELECT employee_id, last_name, manager_id, LEVEL
FROM employees
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id;This query starts at the employee with no manager and walks down. It joins each parent's employee_id to the manager_id of its children. LEVEL reports the depth of each row, where the starting rows are level 1.
With the HR sample data, the first rows look like this:
| EMPLOYEE_ID | LAST_NAME | MANAGER_ID | LEVEL |
|---|---|---|---|
| 100 | King | 1 | |
| 101 | Kochhar | 100 | 2 |
| 108 | Greenberg | 101 | 3 |
| 109 | Faviet | 108 | 4 |
King is the root. Kochhar reports to King, and Greenberg reports to Kochhar. Faviet reports to Greenberg and sits at level 4. The result also shows that Oracle lists a row's descendants before it moves to the next sibling.
What each clause does
START WITH is optional. It takes any condition you could put in a WHERE clause, and every row that satisfies it becomes a root. These rows form level 1 of the result. The condition can compare columns, call functions or contain a subquery.
CONNECT BY is required. Its condition is evaluated between a row that has already been selected, called the parent row, and each candidate row in the table. A candidate that satisfies the condition becomes a child. The keyword PRIOR marks which side of the comparison comes from the parent row. Without it, the condition would compare two columns of the same candidate row. The next chapter covers PRIOR in detail. For now, read PRIOR employee_id = manager_id as "the child's manager_id equals the parent's employee_id".
How Oracle evaluates the query
Oracle builds the result in repeated passes:
- It finds all rows that satisfy
START WITH. These are the roots and form level 1. - For each row at the current level, it searches the table for rows that satisfy
CONNECT BYwith that row as the parent. - Those rows become the next level, and the process repeats.
- It stops when a pass finds no new children.
- It applies any remaining
WHEREconditions and returns the rows.
The same table is read at every pass, so a row can appear in the result more than once if it is reachable by more than one path. In a clean tree each employee has one manager, so each row appears once.
Row order without ORDER BY
Hierarchical queries return rows in depth-first order. Oracle returns a parent, then its first child, then that child's descendants, and only then the parent's next child. This keeps each subtree together, which is why the output reads like an outline.
A regular ORDER BY sorts the final result and destroys this grouping. If you add ORDER BY last_name, the rows come back alphabetically with no regard for the tree. To sort within each branch and keep the tree intact, use ORDER SIBLINGS BY, which a later chapter covers.
Choosing the starting point
The START WITH condition decides which part of the tree you see. You can change it without touching CONNECT BY.
SELECT employee_id, last_name, LEVEL
FROM employees
START WITH employee_id = 101
CONNECT BY PRIOR employee_id = manager_id;This returns Kochhar and everyone below Kochhar, with Kochhar at level 1. LEVEL is always relative to the starting rows, not to the top of the whole company.
Several rows can match START WITH, and then the result is a forest, meaning several trees. For example, START WITH department_id = 60 makes every employee in department 60 a root. Their descendants are returned under each of them.
You can leave out START WITH altogether. Every row in the table then counts as a root, and Oracle walks down from each one. A later chapter uses this form for aggregation. Most of the time it produces many duplicate-looking rows, so leave START WITH out only on purpose.
Where the clauses sit in a statement
The hierarchical clause comes after FROM and any WHERE, and before GROUP BY and ORDER BY:
SELECT employee_id, last_name, LEVEL
FROM employees
WHERE salary > 3000
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id
ORDER BY employee_id;If the query joins tables in the FROM clause, Oracle resolves the joins first and then builds the hierarchy from the joined rows. A WHERE condition that is not part of a join filters rows after the hierarchy is built. It removes only the rows that fail it. Their children stay in the result, and the later chapter on pruning shows how to cut off whole branches.
Common errors
Forgetting PRIOR. Without PRIOR, CONNECT BY employee_id = manager_id compares two columns of the same candidate row. Almost no row has employee_id equal to manager_id, so the query returns only the root rows.
Reversing the columns by accident. Suppose you write START WITH manager_id IS NULL and CONNECT BY PRIOR manager_id = employee_id. This walks upward from the root, and the root has no manager, so the query returns a single row. Direction depends on which column carries PRIOR. The chapter on bottom-up queries covers that.
A START WITH condition that matches nothing. If no row satisfies it, the query returns no rows and no error. Check the condition on its own with a plain SELECT ... WHERE. A typical cause is comparing against NULL with = instead of IS NULL.
Looping data. If employee A reports to B and B reports to A, Oracle detects that a row is its own ancestor and raises ORA-01436: CONNECT BY loop in user data. Fix the data or use NOCYCLE, which a later chapter explains.
Sorting with a plain ORDER BY. As noted above, this flattens the tree order. Use it only when you do not care about the tree layout.
Putting it together
The two clauses answer two separate questions. START WITH answers "which rows are the tops of the trees?" and CONNECT BY answers "given a row, which rows are its children?" Keep them separate in your head and you can change either one without breaking the other. Changing START WITH selects a different subtree. Changing CONNECT BY changes how rows are related.
Exercise
Write a query that lists employee 101 (Kochhar) and everyone who reports to Kochhar directly or indirectly, showing employee_id, last_name and LEVEL. What LEVEL value does Kochhar get, and why?
Show answer
SELECT employeeid, lastname, LEVEL FROM employees START WITH employeeid = 101 CONNECT BY PRIOR employeeid = manager_id; Kochhar gets LEVEL 1 because LEVEL is counted from the rows that satisfy START WITH, not from the top of the whole company.
Exercise
A colleague writes START WITH manager_id IS NULL CONNECT BY employee_id = manager_id and gets back only one row. What is wrong, and how do you fix it?
Show answer
The CONNECT BY condition has no PRIOR, so it compares two columns of the same candidate row and no row qualifies as a child. Only the root row from START WITH is returned. Fix it by writing CONNECT BY PRIOR employeeid = managerid.