Sub topic 9
Building paths and finding the root
This chapter covers two operators that carry information along a hierarchy: SYS_CONNECT_BY_PATH builds the route from the root to each row, and CONNECT_BY_ROOT returns a value from the row where that route started. It assumes you can already write a top-down query with START WITH, CONNECT BY PRIOR and LEVEL, and that you know the HR-style employees table, where manager_id points to employee_id in the same table.
Why you need them
LEVEL tells you how deep a row is, but not how it got there. Two questions come up often:
- What is the chain of names from the top of the organization down to this person?
- Which top-level manager does this person ultimately belong to?
A plain hierarchical query can answer both only by joining repeatedly. Oracle provides one operator and one pseudo-operator that answer them directly, in a single pass over the tree.
SYS_CONNECT_BY_PATH
SYS_CONNECT_BY_PATH(column, separator) returns the values of column for every row on the path from the root to the current row. The values are joined with the separator, and the separator also starts the string.
SELECT last_name,
SYS_CONNECT_BY_PATH(last_name, '/') AS path
FROM employees
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id;A row for an employee two levels below the root might show /King/Kochhar/Whalen. The root row shows just /King.
Rules to remember:
- It is valid only in a hierarchical query. Using it without
CONNECT BYraises an error. - The separator must be a literal string. You cannot pass a column or an expression.
- The column can be any expression that converts to a string, so
SYS_CONNECT_BY_PATH(employee_id, '.')gives a dotted ID path. - The result is a
VARCHAR2with a limit of 4000 bytes. A deep tree with long values can exceed it and raiseORA-30004. - The separator must not appear inside the values. If it does, you can no longer split the path reliably. Oracle raises
ORA-30004when the separator occurs in a column value.
Removing the leading separator
Because the path starts with the separator, most reports trim it:
SELECT last_name,
LTRIM(SYS_CONNECT_BY_PATH(last_name, '/'), '/') AS path
FROM employees
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id;Use SUBSTR(path, 2) if the first character of a value could itself be the separator, since LTRIM removes every leading occurrence.
CONNECT_BY_ROOT
CONNECT_BY_ROOT is a unary operator. Placed before a column or expression, it returns that expression's value from the root row of the current row's path.
SELECT last_name,
CONNECT_BY_ROOT last_name AS top_manager
FROM employees
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id;With a single root, every row shows the same top_manager. It becomes useful in two situations:
- Your
START WITHmatches several rows, so the data is a forest. Each row reports the root of its own tree. - You omit
START WITH, so every row is a root of its own traversal, and you group by the root. The aggregation chapter builds on this.
Rules for CONNECT_BY_ROOT:
- It is not allowed in the
START WITHorCONNECT BYclauses themselves. - It binds to the expression that follows it. Write
CONNECT_BY_ROOT last_name || ' team'carefully: the operator applies only tolast_name. To apply it to a whole expression, wrap that expression in parentheses. - It works with any column, not only names.
CONNECT_BY_ROOT salaryreturns the root's salary.
Using both together
The two operators appear naturally in the same query.
SELECT last_name,
SYS_CONNECT_BY_PATH(last_name, '/') AS path,
CONNECT_BY_ROOT last_name AS top_manager,
CONNECT_BY_ISLEAF AS is_leaf
FROM employees
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id;For each row, path is the route from the root, top_manager is the root's name, and is_leaf is 1 when the row has no children. The leaf flag is covered in the next chapter.
The diagram below shows how the values accumulate as Oracle walks down one branch.
Practical uses
Building a path with a depth check
Combine the path with LEVEL to find rows whose route has a certain shape. This returns everyone exactly three levels below the root, together with their route.
SELECT employee_id,
SYS_CONNECT_BY_PATH(last_name, '/') AS path
FROM employees
WHERE LEVEL = 4
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id;The WHERE filter is applied after the hierarchy is built, so the path is complete even though only level 4 rows are returned.
Filtering by the root
Because CONNECT_BY_ROOT is a normal expression in the select list, you can filter on it in an outer query. Use an inline view, since WHERE cannot reference a select-list alias directly.
SELECT *
FROM (
SELECT employee_id,
last_name,
CONNECT_BY_ROOT last_name AS top_manager
FROM employees
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id
)
WHERE top_manager = 'King';You can also write WHERE CONNECT_BY_ROOT last_name = 'King' directly in the same query block.
Bottom-up queries
In an upward traversal, the roles reverse. The starting row is the root of the walk, and the path runs from that row up to the top of the organization.
SELECT employee_id,
last_name,
SYS_CONNECT_BY_PATH(last_name, '>') AS upward_path,
CONNECT_BY_ROOT last_name AS start_person
FROM employees
START WITH employee_id = 107
CONNECT BY employee_id = PRIOR manager_id;Here CONNECT_BY_ROOT returns the employee you started from, not the top executive. The path reads from the employee upward. The "root" of a traversal is always the row selected by START WITH, whatever direction you walk.
Common errors
| Symptom | Cause | Fix | Column |
|---|---|---|---|
| `ORA-30004: when using SYS_CONNECT_BY_PATH function, cannot have separator as part of column value` | A value contains the separator character. | Choose a separator that cannot occur in the data, such as `' | '` or a control character. |
| `ORA-01489: result of string concatenation is too long` or a truncated path | The path exceeded 4000 bytes. | Use shorter values such as IDs, or limit the depth. | |
| `ORA-30929` or `ORA-01788`-style errors when the operator is used without a hierarchy | `SYS_CONNECT_BY_PATH` or `CONNECT_BY_ROOT` used in a query with no `CONNECT BY`. | Add a `CONNECT BY` clause. | |
| Every row shows the same root in a query where you expected several | `START WITH` matches one row only. | Widen `START WITH`, or remove it to treat every row as a root. | |
| Unexpected root values in a bottom-up query | The root is the `START WITH` row, which is the bottom of the tree in an upward walk. | Read the root as the starting point, not the organizational top. |
Choosing the value to put in the path
The choice of column changes what the path is good for.
- Names are readable but may contain the separator or be long.
- Primary key values are short, unique and safe, and they let you join back to the table.
- A zero-padded ID such as
LPAD(employee_id, 6, '0')makes the path sortable as a string, so sorting by path produces a depth-first order.
SELECT LPAD(' ', 2 * (LEVEL - 1)) || last_name AS org_chart,
SYS_CONNECT_BY_PATH(LPAD(employee_id, 6, '0'), '/') AS id_path
FROM employees
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id
ORDER BY id_path;Sorting by the path orders each parent before its children. Be aware that this orders siblings by ID. For alphabetical siblings, use ORDER SIBLINGS BY as in the earlier chapter.
Exercises
Exercise
Write a query that shows, for every employee, the full ID path from the top manager (separated by '/') and the name of the top manager. Start from the employee who has no manager.
Show answer
SELECT employeeid, SYSCONNECTBYPATH(employeeid, '/') AS idpath, CONNECTBYROOT lastname AS topmanager FROM employees START WITH managerid IS NULL CONNECT BY PRIOR employeeid = manager_id;
Exercise
In the query START WITH employeeid = 107 CONNECT BY employeeid = PRIOR managerid, what does CONNECTBYROOT lastname return for each row, and why?
Show answer
It returns the last name of employee 107 on every row. The root of a traversal is the row chosen by START WITH. In a bottom-up walk that row is the starting employee, not the top executive.
Exercise
Your path query fails with ORA-30004. Give the likely cause and one fix.
Show answer
A value in the column passed to SYSCONNECTBYPATH contains the separator character. Use a separator that cannot appear in the data, or pass a column such as employeeid that cannot contain it.