Sub topic 4
Depth in the tree with LEVEL
This chapter assumes you can write a basic hierarchical query with START WITH, CONNECT BY and PRIOR. It also assumes you know the employees table, where manager_id points back to employee_id in the same table. The chapter explains the LEVEL pseudocolumn: what it holds, where you can use it, and the mistakes people make with it.
What LEVEL is
LEVEL is a pseudocolumn. It is not stored in the table. Oracle computes it for each row while it walks the tree. It is a number that tells you how many steps the row is from the starting row:
- Rows picked by
START WITHare at level 1. These are the roots of the query. - Their children are at level 2.
- Their grandchildren are at level 3, and so on.
Here is the first example from the plan again:
SELECT employee_id, last_name, manager_id, LEVEL
FROM employees
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id;The employee with no manager gets LEVEL 1. Employees who report directly to that person get 2. Each row's LEVEL is its parent's LEVEL plus one.
LEVEL only means something in a hierarchical query. Outside one, it returns 0 in Oracle 10g and later. You will see this in the row generation chapter, where LEVEL is used on its own.
How LEVEL relates to the starting rows
LEVEL counts from the rows that START WITH selects, not from the top of the whole table. If you start in the middle of the tree, that row is level 1.
SELECT employee_id, last_name, LEVEL
FROM employees
START WITH employee_id = 101
CONNECT BY PRIOR employee_id = manager_id;Employee 101 is level 1 here, even if that person is several steps below the company head. Direct reports are level 2. The numbers describe distance from your chosen start, not rank in the company.
The same rule applies to bottom-up queries. In the query that starts at employee 107 and follows PRIOR manager_id, employee 107 is level 1. The direct manager is level 2, and the level rises as you move toward the top. Higher numbers then mean "further up", which is the reverse of what you may expect.
If START WITH matches several rows, all of them are level 1. A tree with more than one root is called a forest, and each root begins its own branch.
Where you can use LEVEL
You can use LEVEL in several places in a hierarchical query.
| Clause | Example use |
|---|---|
| `SELECT` list | Show the depth, or build indentation from it |
| `WHERE` | `WHERE LEVEL <= 3` keeps only rows in the top three levels |
| `CONNECT BY` | `CONNECT BY ... AND LEVEL <= 3` stops the walk at level 3 |
| `ORDER BY` | Sort by depth, though this breaks the tree order |
| Expressions | `LEVEL * 10`, `LPAD(...)`, `CASE WHEN LEVEL = 1 ...` |
Two of these look alike but behave differently, so look at them closely.
Limiting depth: WHERE versus CONNECT BY
Both of these queries return employees in the top three levels:
SELECT employee_id, last_name, LEVEL
FROM employees
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id
AND LEVEL <= 3;SELECT employee_id, last_name, LEVEL
FROM employees
WHERE LEVEL <= 3
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id;For this simple condition the results match. The work done is not the same:
- With the condition in
CONNECT BY, Oracle stops going deeper once the limit is reached. Rows below level 3 are never visited. - With the condition in
WHERE, Oracle may still walk the whole tree. It builds every row, then discards the deep ones.
On a large hierarchy the first form can be much cheaper. The next chapters cover this difference between filtering and pruning in more detail. For depth limits, putting LEVEL in CONNECT BY is the better habit.
Using LEVEL to show structure
A level number by itself is hard to read. You can use it to build indentation. The plan covers this fully in a later chapter, but a short version shows how LEVEL is used as a value:
SELECT LEVEL,
LPAD(' ', 2 * (LEVEL - 1)) || last_name AS org_chart
FROM employees
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id;LEVEL - 1 is 0 for the root, so the root gets no padding. Each deeper level adds two more spaces.
Summarizing by level
Because LEVEL is an ordinary number in the query, you can group on it. This counts how many employees sit at each depth and finds the widest level of the tree:
SELECT LEVEL AS depth,
COUNT(*) AS employees_at_depth
FROM employees
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id
GROUP BY LEVEL
ORDER BY LEVEL;To find the deepest point of the tree, take the maximum:
SELECT MAX(LEVEL) AS tree_height
FROM employees
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id;GROUP BY LEVEL and MAX(LEVEL) work because Oracle builds the hierarchy first and then applies grouping to the result.
Order of evaluation
The order in which Oracle processes the clauses explains most LEVEL surprises.
Two points follow from this order:
LEVELis assigned during the walk, soWHERE LEVEL = 2removes rows only after the tree has been built. The levels were already set correctly.- A
WHEREcondition on a normal column does not changeLEVELfor other rows. If a manager is removed byWHERE, the manager's reports keep their original level numbers. This leaves gaps in the output.
Oracle has one exception to the WHERE timing. If the query uses a join in FROM, Oracle applies the join conditions first, then builds the hierarchy, and only then applies the remaining WHERE conditions. In practice, keep join logic in the FROM clause with JOIN ... ON when you mix joins and hierarchies, so the intent is clear.
Common errors
Using LEVEL without CONNECT BY. In a normal query, LEVEL is not a depth. Oracle treats it as a hierarchical pseudocolumn only when the query has a CONNECT BY clause. Without one, you may get an error or a meaningless value.
Expecting LEVEL to be a global rank. It counts from the starting rows. If you change START WITH, the numbers shift. Do not store LEVEL values and assume they describe where the employee sits in the whole company.
Reading bottom-up levels as seniority. In a query that follows PRIOR manager_id, a bigger LEVEL means a more senior person. Label this clearly in your output if others will read it.
Sorting by LEVEL and losing the tree. ORDER BY LEVEL returns all level 1 rows, then all level 2 rows, and so on. This is a flat, layer-by-layer view. It does not keep children under their parents. To keep the tree shape, omit ORDER BY, or use ORDER SIBLINGS BY, which is the subject of a later chapter.
Filtering with WHERE and expecting a shorter walk. As shown above, WHERE LEVEL <= n does not stop the traversal early. Use the CONNECT BY form when performance matters.
Confusing LEVEL with CONNECTBYROOT. LEVEL is the depth of the current row. CONNECT_BY_ROOT gives a column value from the level 1 ancestor. They answer different questions.
Using LEVEL with CASE
You can label rows by depth with a normal expression:
SELECT last_name,
LEVEL,
CASE LEVEL
WHEN 1 THEN 'Head'
WHEN 2 THEN 'Director'
ELSE 'Staff'
END AS role_label
FROM employees
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id;This is useful for reports, but the labels come from position in the tree. If the tree changes, so do the labels.
Exercises
Exercise
A query uses START WITH employee_id = 101 and CONNECT BY PRIOR employee_id = manager_id. What LEVEL does employee 101 get, and why?
Show answer
Level 1. LEVEL counts from the rows chosen by START WITH, so the starting row is level 1 no matter where that employee sits in the full company tree. Direct reports are level 2.
Exercise
Write a query that returns the number of employees at each depth of the full organization, starting from the employee with no manager, ordered by depth.
Show answer
SELECT LEVEL AS depth, COUNT(*) AS employeesatdepth FROM employees START WITH managerid IS NULL CONNECT BY PRIOR employeeid = manager_id GROUP BY LEVEL ORDER BY LEVEL;
Exercise
Why is CONNECT BY PRIOR employee_id = manager_id AND LEVEL <= 3 usually cheaper than putting WHERE LEVEL <= 3 on a large tree?
Show answer
The condition in CONNECT BY stops Oracle from following branches deeper than level 3, so those rows are never built. A WHERE condition is applied after the hierarchy is built, so Oracle may still walk the whole tree and then discard the deep rows.