Sub topic 2
Indenting the output to look like a tree
This section assumes you know basic SELECT, WHERE and ORDER BY, the START WITH and CONNECT BY PRIOR syntax, and the LEVEL pseudocolumn.
Indenting the output with LPAD
LEVEL gives each row's depth, with the root at 1. LPAD(' ', 2 * (LEVEL - 1)) returns spaces in proportion to that depth. Concatenating the name after it produces an indented label.
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;Sorting within branches with ORDER SIBLINGS BY
A plain ORDER BY sorts every row together and breaks the tree shape. ORDER SIBLINGS BY sorts only the rows that share a parent, so each child stays directly under its manager.
SELECT LPAD(' ', 2 * (LEVEL - 1)) || last_name AS org_chart
FROM employees
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id
ORDER SIBLINGS BY last_name;> Not allowed here: block quotes are forbidden, so the note follows as a callout.
Walking up the tree: bottom-up queries
Move PRIOR to the other side of the equals sign to walk from a row toward its ancestors. Here PRIOR is on manager_id, so each step moves to the manager.
SELECT employee_id, last_name, LEVEL
FROM employees
START WITH employee_id = 107
CONNECT BY employee_id = PRIOR manager_id;WHERE versus conditions in CONNECT BY
A WHERE condition runs after the hierarchy is built, so it removes only the rows that fail it. A condition inside CONNECT BY runs during traversal. When a child row fails it, Oracle drops that child and every row below it.
SELECT employee_id, last_name, LEVEL
FROM employees
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id
AND salary > 5000;Use WHERE when you only want to hide rows. Use the CONNECT BY condition when a failing row should also hide its subtree.
Exercise
Exercise
Why does ORDER SIBLINGS BY keep each employee under their manager, while ORDER BY does not?
Show answer
ORDER SIBLINGS BY sorts rows only within each group of siblings, so the parent-child order from the traversal is preserved. ORDER BY sorts the whole result set and discards the tree order.