Sub topic 1
Tree data in a self-referencing table
This chapter explains how a parent-child relationship is stored in one table. Later chapters query that structure with CONNECT BY. Here you build the table and learn to read it. You also learn where plain joins stop working.
Prerequisites
This chapter assumes you already know the following:
- Basic
SELECT,WHEREandORDER BYin SQL. - What primary keys and foreign keys are, and how a foreign key points at a primary key.
- How a self-join works: a table joined to itself under two aliases.
- The Oracle
DUALtable, a one-row table used for queries that need no real data.
You do not need any hierarchical SQL yet. Every example in this chapter uses ordinary SQL.
What hierarchical data looks like
Hierarchical data is data where each item has at most one parent and can have many children. Examples include:
- An organization chart, where each employee reports to one manager.
- A folder tree, where each folder sits inside one other folder.
- A parts list, where each assembly is made of sub-assemblies.
- A category tree in a shop, such as Electronics, then Computers, then Laptops.
The shape is a tree. These terms are used throughout the tutorial:
| Term | Meaning |
|---|---|
| Root | A row with no parent. It is the top of the tree. |
| Parent | The row one step above a given row. |
| Child | A row one step below a given row. |
| Siblings | Rows that share the same parent. |
| Leaf | A row with no children. |
| Ancestor | Any row above a given row: its parent, its parent's parent, and so on. |
| Descendant | Any row below a given row. |
| Depth | The number of steps from the root to a row. |
The self-referencing table
A relational table has no built-in tree type. The usual way to store a tree is the adjacency list model. Each row holds a reference to its parent's key in the same table. This is a foreign key that points back to the table's own primary key. That design is called a self-referencing table.
In an employee table, employee_id is the primary key. A column named manager_id holds the employee_id of the person's manager. The root row, the top manager, has NULL in manager_id, because nobody manages that person.
The following script creates a small table you can reuse in later chapters. The data is a simplified version of a typical sample employee table.
CREATE TABLE employees (
employee_id NUMBER(6) PRIMARY KEY,
last_name VARCHAR2(25) NOT NULL,
manager_id NUMBER(6),
salary NUMBER(8,2),
CONSTRAINT emp_manager_fk
FOREIGN KEY (manager_id) REFERENCES employees (employee_id)
);
INSERT INTO employees VALUES (100, 'King', NULL, 24000);
INSERT INTO employees VALUES (101, 'Kochhar', 100, 17000);
INSERT INTO employees VALUES (102, 'De Haan', 100, 17000);
INSERT INTO employees VALUES (103, 'Hunold', 102, 9000);
INSERT INTO employees VALUES (104, 'Ernst', 103, 6000);
INSERT INTO employees VALUES (105, 'Austin', 103, 4800);
INSERT INTO employees VALUES (108, 'Greenberg', 101, 12000);
INSERT INTO employees VALUES (109, 'Faviet', 108, 9000);
INSERT INTO employees VALUES (110, 'Chen', 108, 8200);
COMMIT;The foreign key emp_manager_fk references the table it belongs to. Oracle checks it like any other foreign key. You cannot insert an employee whose manager_id does not exist, and you cannot delete a manager who still has reports. This is why the rows are inserted from the top down: King must exist before anyone can point at King.
The data in the table is:
| employee_id | last_name | manager_id |
|---|---|---|
| 100 | King | NULL |
| 101 | Kochhar | 100 |
| 102 | De Haan | 100 |
| 103 | Hunold | 102 |
| 104 | Ernst | 103 |
| 105 | Austin | 103 |
| 108 | Greenberg | 101 |
| 109 | Faviet | 108 |
| 110 | Chen | 108 |
Read the table one row at a time. Row 103 has manager_id 102, so Hunold reports to De Haan. Row 100 has no manager, so King is the root.
The tree behind the rows
The same data drawn as a tree is easier to see. An arrow points from a manager to the people who report to them.
In this tree:
- King is the only root.
- Kochhar and De Haan are siblings.
- Faviet, Chen, Ernst and Austin are leaves.
- Faviet's ancestors are Greenberg, Kochhar and King.
- King's descendants are all eight other employees.
Reading one level with a self-join
You already know a way to follow the parent link: a self-join. Join the table to itself, matching the child's manager_id to the parent's employee_id.
SELECT e.last_name AS employee,
m.last_name AS manager
FROM employees e
LEFT JOIN employees m
ON e.manager_id = m.employee_id
ORDER BY e.employee_id;The result is:
| EMPLOYEE | MANAGER |
|---|---|
| King | NULL |
| Kochhar | King |
| De Haan | King |
| Hunold | De Haan |
| Ernst | Hunold |
| Austin | Hunold |
| Greenberg | Kochhar |
| Faviet | Greenberg |
| Chen | Greenberg |
A LEFT JOIN is needed here. With an inner join, King would disappear, because King has no matching manager row.
A self-join shows exactly one step. Each row appears with its direct manager and nothing further.
Where fixed joins break down
Suppose you want everyone who reports to King, directly or indirectly. With plain joins you must add one join for each level:
SELECT e1.last_name AS level_1,
e2.last_name AS level_2,
e3.last_name AS level_3,
e4.last_name AS level_4
FROM employees e1
LEFT JOIN employees e2 ON e2.manager_id = e1.employee_id
LEFT JOIN employees e3 ON e3.manager_id = e2.employee_id
LEFT JOIN employees e4 ON e4.manager_id = e3.employee_id
WHERE e1.manager_id IS NULL;This query has three problems:
- It only reaches four levels. If a fifth level appears, the query silently misses it.
- It returns one wide row per path, not one row per employee. Leaf rows are padded with
NULLvalues. - You must know the maximum depth before you write the query, and the depth can change whenever someone is hired.
The core issue is that the depth of a tree is data, not structure. A query whose shape is fixed in advance cannot follow a path of unknown length. What you need is a way to say "keep following the parent link until there are no more rows." That is what CONNECT BY does. The next chapter introduces START WITH and CONNECT BY.
Design points and edge cases
Several properties of the adjacency list model affect the queries you write later.
- The root is marked by NULL. The
manager_id IS NULLtest is the usual way to find a root. A table can contain more than one root. Such a table holds a forest, which is several separate trees. - A column is nullable by design. The
manager_idcolumn must allowNULL. If you mark itNOT NULL, you cannot insert the root row unless you make it point at itself. Pointing a root at itself is a different convention, and it creates a loop, which later chapters treat as a cycle. - The foreign key does not prevent cycles. The constraint only checks that the referenced manager exists. It does not check that the chain of managers ends. If you update King's
manager_idto 109, every row is still valid under the foreign key, but King now reports, indirectly, to himself. Hierarchical queries on such data need special handling. - The model gives one parent per row. A row has one
manager_id, so each employee has at most one manager. A structure where an item can have two parents, such as a part used in two assemblies, is a graph, not a tree. It needs a separate link table. - Keys must be indexed.
employee_idis already indexed because it is the primary key.manager_idhas no index unless you create one. Oracle does not create indexes for foreign keys automatically. Searching for the children of a row is the core operation of a hierarchical query, so an index onmanager_idmatters. Chapter 15 covers this. - The tree is implied, not stored. Nothing in the table records depth, path or number of descendants. Every such fact must be computed by a query. The cost is query complexity. The benefit is that moving a whole branch to a new manager is one
UPDATEof one row.
Check your understanding
Exercise
In the sample table, which rows are leaves, and how can you find them with ordinary SQL (no CONNECT BY)?
Show answer
The leaves are Ernst (104), Austin (105), Faviet (109) and Chen (110). A leaf is a row whose employeeid never appears as a managerid. One way to find them is: SELECT employeeid, lastname FROM employees e WHERE NOT EXISTS (SELECT 1 FROM employees c WHERE c.managerid = e.employeeid);
Exercise
Why does the self-join example use LEFT JOIN, and what changes if you use an inner JOIN?
Show answer
King has manager_id NULL, so no manager row matches him. A LEFT JOIN keeps King and shows NULL for the manager. An inner JOIN drops King, so the result has eight rows instead of nine.
Exercise
A colleague updates King's manager_id to 109 and the update succeeds. Why does the foreign key not reject it, and what is the problem?
Show answer
Employee 109 exists, so the foreign key is satisfied. The foreign key checks only that the referenced row exists, not that the chain of managers ends. King now has an indirect path to himself (King, Faviet, Greenberg, Kochhar, King), which is a cycle. The table no longer has a root, and hierarchical queries on it need cycle handling.