Sub topic 1
Tree Data in a Self-Referencing Table
Prerequisites
This chapter assumes you can write basic SELECT, WHERE and ORDER BY queries, that you understand primary and foreign keys, that you can write a self-join, and that you have used the Oracle DUAL table.
Tree data in a self-referencing table
A self-referencing table stores rows that point to other rows in the same table. In an employee table, each row has a manager_id that matches the employee_id of another employee. The top of the tree has a NULL manager_id.
| employee_id | last_name | manager_id |
|---|---|---|
| 100 | King | NULL |
| 101 | Kochhar | 100 |
| 108 | Greenberg | 101 |
Your first hierarchical query
START WITH chooses the root rows, and CONNECT BY defines how each row links to its children. Oracle then walks the tree from the roots downward.
SELECT employee_id, last_name, manager_id, LEVEL
FROM employees
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id;> Note: START WITH and CONNECT BY are Oracle-specific syntax. Standard SQL uses recursive WITH instead.
What PRIOR refers to
PRIOR marks the column taken from the parent row. In CONNECT BY PRIOR employee_id = manager_id, the parent's employee_id must equal the child's manager_id. A common error is placing PRIOR on the wrong side, which walks the tree in the wrong direction. If the data contains a loop, Oracle raises ORA-01436.
Depth in the tree with LEVEL
LEVEL is a pseudocolumn that returns the depth of each row. Roots have LEVEL 1, their children have 2, and so on. The next query indents each name by its depth.
SELECT LPAD(' ', 2 * (LEVEL - 1)) || last_name AS org_chart,
LEVEL
FROM employees
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id;Exercise
Which rows does START WITH manager_id IS NULL return, and what is their LEVEL?
Show answer
It returns the root rows, the employees with no manager. Their LEVEL is 1.