Sub topic 5
Indenting the Output to Look Like a Tree
Prerequisites and the basic idea
This chapter assumes that you know basic SELECT, WHERE, and ORDER BY syntax, and that you understand a self-referencing table. A self-referencing table has a foreign key that points back to the same table. In employees, manager_id points to another employee's employee_id.
A hierarchical query returns rows in parent-to-child order. Oracle provides the LEVEL pseudocolumn to show each row's depth:
- The root employee has
LEVEL = 1. - A direct report has
LEVEL = 2. - A report of that employee has
LEVEL = 3.
You can turn the depth into indentation with LPAD. LPAD is a function that pads a string on its left until it reaches a specified length.
SELECT employee_id,
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;For the root row, 2 * (LEVEL - 1) is zero, so the name has no indentation. Each level below the root adds two spaces.
The || operator concatenates strings. Therefore, the query first creates the spaces and then joins those spaces to last_name.
How the hierarchy is displayed
Suppose the data contains this structure:
The query produces output similar to this:
| Org chart | Level |
|---|---|
| King | 1 |
| Kochhar | 2 |
| Greenberg | 3 |
| De Haan | 2 |
The spaces are part of the org_chart value. They do not change the underlying employee data.
You can include the identifiers while testing, then remove them from the final display:
SELECT LPAD(' ', 2 * (LEVEL - 1)) || last_name AS org_chart,
employee_id,
manager_id,
LEVEL AS depth
FROM employees
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id;The manager_id column helps verify that each row is attached to the expected parent. The depth alias makes the purpose of LEVEL clearer to users reading the result.
Keeping siblings together
Employees who share a manager are siblings. Use ORDER SIBLINGS BY to sort those employees without breaking the hierarchy.
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
ORDER SIBLINGS BY last_name;Oracle sorts names alphabetically within each manager's group. It still prints all descendants of one employee beneath that employee before moving to the next sibling.
An ordinary final ORDER BY last_name is different. It can sort the complete result set alphabetically and destroy the visual parent-child order.
Exercise
What indentation does an employee with LEVEL = 4 receive when the query uses LPAD(' ', 2 * (LEVEL - 1))?
Show answer
The expression produces six spaces because 2 * (4 - 1) equals 6.