Sub topic 10
Finding leaf rows with CONNECT_BY_ISLEAF
A leaf is a row in a hierarchy that has no children. In an employee table, a leaf is a person who manages nobody. Oracle can tell you which returned rows are leaves with the CONNECT_BY_ISLEAF pseudocolumn, so you don't need a second query or a self-join.
This chapter assumes you can write a basic START WITH ... CONNECT BY PRIOR query, that you know what LEVEL and ORDER SIBLINGS BY do, and that you have seen the difference between top-down and bottom-up traversal.
The sample data
The examples use a small table so you can run every query and check the output by hand.
CREATE TABLE staff (
emp_id NUMBER PRIMARY KEY,
name VARCHAR2(20) NOT NULL,
mgr_id NUMBER REFERENCES staff (emp_id),
salary NUMBER NOT NULL
);
INSERT INTO staff VALUES (1, 'Alice', NULL, 9000);
INSERT INTO staff VALUES (2, 'Bob', 1, 7000);
INSERT INTO staff VALUES (3, 'Carol', 1, 6500);
INSERT INTO staff VALUES (4, 'Dave', 2, 4000);
INSERT INTO staff VALUES (5, 'Erin', 2, 4500);
INSERT INTO staff VALUES (6, 'Frank', 3, 3000);
INSERT INTO staff VALUES (7, 'Gina', 4, 2500);
COMMIT;The tree looks like this. Erin, Frank, and Gina manage nobody, so they are the leaves.
What the pseudocolumn returns
CONNECT_BY_ISLEAF returns 1 if the current row has no child that satisfies the CONNECT BY condition. Otherwise it returns 0. It is valid only in a query that has a CONNECT BY clause.
SELECT LPAD(' ', 2 * (LEVEL - 1)) || name AS org_chart,
LEVEL,
CONNECT_BY_ISLEAF AS is_leaf
FROM staff
START WITH mgr_id IS NULL
CONNECT BY PRIOR emp_id = mgr_id
ORDER SIBLINGS BY name;The result is:
| org_chart | LEVEL | is_leaf |
|---|---|---|
| Alice | 1 | 0 |
| Bob | 2 | 0 |
| Dave | 3 | 0 |
| Gina | 4 | 1 |
| Erin | 3 | 1 |
| Carol | 2 | 0 |
| Frank | 3 | 1 |
Notice that leaves appear at different depths. Gina is at level 4 and Erin and Frank are at level 3. Depth and leaf status are separate properties. A row can be deep and still have children, and a row near the top can be a leaf.
Filtering to leaves only
Put the condition in WHERE:
SELECT emp_id, name, LEVEL
FROM staff
WHERE CONNECT_BY_ISLEAF = 1
START WITH mgr_id IS NULL
CONNECT BY PRIOR emp_id = mgr_id
ORDER SIBLINGS BY name;This returns Gina, Erin, and Frank.
Oracle builds the full tree first and evaluates CONNECT_BY_ISLEAF during that traversal. It applies the WHERE filter afterward. Two consequences follow:
- Removing rows with
WHEREdoes not change whether the remaining rows are leaves. If you writeWHERE name <> 'Gina', Dave still reportsCONNECT_BY_ISLEAF = 0, because Gina was part of the tree when Dave was evaluated. - Filtering on
CONNECT_BY_ISLEAFdoes not stop Oracle from traversing the non-leaf rows. It reads the whole tree and discards the rows you don't want.
Labeling rows by role
A common use is labeling each row. A CASE expression turns the flag into readable text:
SELECT LPAD(' ', 2 * (LEVEL - 1)) || name AS org_chart,
CASE CONNECT_BY_ISLEAF
WHEN 1 THEN 'individual contributor'
ELSE 'manager'
END AS role
FROM staff
START WITH mgr_id IS NULL
CONNECT BY PRIOR emp_id = mgr_id
ORDER SIBLINGS BY name;This works for report output, such as marking folders and files in a directory tree or categories and products in a catalog.
Leaf status depends on the CONNECT BY condition
The definition says "no child that satisfies the CONNECT BY condition". That wording matters when you prune a branch. A row whose only children are excluded by the condition becomes a leaf in the query result, even though it has children in the table.
SELECT name, LEVEL, CONNECT_BY_ISLEAF AS is_leaf
FROM staff
START WITH mgr_id IS NULL
CONNECT BY PRIOR emp_id = mgr_id
AND salary > 4000
ORDER SIBLINGS BY name;Only employees earning more than 4000 are followed. The result is:
| name | LEVEL | is_leaf |
|---|---|---|
| Alice | 1 | 0 |
| Bob | 2 | 0 |
| Erin | 3 | 1 |
| Carol | 2 | 1 |
Carol is flagged as a leaf because her only report, Frank (3000), was pruned. Dave (4000) is not returned, and his subtree is gone with him.
Remember this when you use the flag to mean "has no reports". It actually means "has no reports in this query's tree". If the real business meaning is the first one, check the pruning condition or compute the answer another way.
Bottom-up queries reverse the meaning
A leaf is defined relative to the direction of traversal. In a bottom-up query, the children of a row are its managers, so a leaf is the row with no parent.
SELECT name, LEVEL, CONNECT_BY_ISLEAF AS is_leaf
FROM staff
START WITH emp_id = 7
CONNECT BY emp_id = PRIOR mgr_id;The result is:
| name | LEVEL | is_leaf |
|---|---|---|
| Gina | 1 | 0 |
| Dave | 2 | 0 |
| Bob | 3 | 0 |
| Alice | 4 | 1 |
Gina is the starting row and is flagged 0, even though she is a leaf in the organization. Alice is flagged 1 because the walk can't continue above her. In bottom-up queries, CONNECT_BY_ISLEAF = 1 therefore finds the top of the chain, which is a handy way to identify the root of a given row's tree.
Counting leaves
To count all leaves, filter and count:
SELECT COUNT(*) AS leaf_count
FROM staff
WHERE CONNECT_BY_ISLEAF = 1
START WITH mgr_id IS NULL
CONNECT BY PRIOR emp_id = mgr_id;The result is 3.
To count leaves under each employee, combine the flag with CONNECT_BY_ROOT. Omit START WITH so every row is treated as a root:
SELECT CONNECT_BY_ROOT name AS manager,
SUM(CONNECT_BY_ISLEAF) AS leaf_descendants
FROM staff
CONNECT BY PRIOR emp_id = mgr_id
GROUP BY CONNECT_BY_ROOT name
ORDER BY manager;The result is:
| manager | leaf_descendants |
|---|---|
| Alice | 3 |
| Bob | 2 |
| Carol | 1 |
| Dave | 1 |
| Erin | 1 |
| Frank | 1 |
| Gina | 1 |
A leaf that is its own root counts itself, which is why Erin, Frank, and Gina each show 1. If you want only managers, add HAVING COUNT(*) > 1, since a leaf root produces a single row.
Leaves and cycles
If the data may contain loops, add NOCYCLE. With NOCYCLE, Oracle stops following a row whose child is also one of its ancestors. That row can be flagged as a leaf even though it has a child in the table, because Oracle did not follow the child. If you need to tell a true leaf from a row that stopped because of a loop, select CONNECT_BY_ISCYCLE as well. A row with CONNECT_BY_ISCYCLE = 1 has a child that is also an ancestor.
SELECT emp_id, name,
CONNECT_BY_ISLEAF AS is_leaf,
CONNECT_BY_ISCYCLE AS is_cycle
FROM staff
START WITH emp_id = 1
CONNECT BY NOCYCLE PRIOR emp_id = mgr_id;On the clean sample data, is_cycle is 0 for every row.
Generated rows
CONNECT BY LEVEL <= n also supports the flag. Each generated row has a child until the limit is reached, so only the last row is a leaf:
SELECT LEVEL AS n, CONNECT_BY_ISLEAF AS is_last
FROM dual
CONNECT BY LEVEL <= 3;The result is:
| n | is_last |
|---|---|
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
This is a cheap way to mark the final row of a generated series.
Alternative: NOT EXISTS
You can find leaves without a hierarchical query:
SELECT s.emp_id, s.name
FROM staff s
WHERE NOT EXISTS (SELECT 1 FROM staff c WHERE c.mgr_id = s.emp_id);This returns every row with no children in the table. It is simple and doesn't traverse anything. It does not respect pruning conditions, bottom-up direction, or a subtree chosen by START WITH. Use NOT EXISTS when you need the table-wide answer. Use CONNECT_BY_ISLEAF when the answer must match the rows your hierarchical query returns.
Common mistakes
- Using
CONNECT_BY_ISLEAFin a query with noCONNECT BYclause. The pseudocolumn exists only in hierarchical queries. - Expecting
WHEREto change leaf status. It filters after the tree is built. - Reading
0and1backward.1means leaf. - Forgetting that pruning in
CONNECT BYcan create leaves that have children in the table. - Using
CONNECT_BY_ISLEAF = 1in a bottom-up query and expecting the lowest employees. It returns the top of the chain.
Exercise
Using the staff table, write a query that returns the name and LEVEL of every employee who has no direct reports, starting from the top of the organization and ordering siblings by name. Then explain why adding AND salary > 6000 to the CONNECT BY condition changes which rows are leaves.
Show answer
SELECT name, LEVEL FROM staff WHERE CONNECTBYISLEAF = 1 START WITH mgrid IS NULL CONNECT BY PRIOR empid = mgr_id ORDER SIBLINGS BY name; This returns Gina (4), Erin (3), and Frank (3). Adding AND salary > 6000 prunes every employee earning 6000 or less. Only Alice (9000), Bob (7000), and Carol (6500) remain. Dave and Erin are pruned, so Bob has no qualifying child and becomes a leaf. Carol's only child, Frank, is also pruned, so Carol becomes a leaf as well. A row is a leaf when it has no child that satisfies the CONNECT BY condition, not when it has no child in the table.
Exercise
What does this query return for CONNECTBYISLEAF on each row, and why? SELECT name, CONNECTBYISLEAF AS isleaf FROM staff START WITH empid = 5 CONNECT BY empid = PRIOR mgrid;
Show answer
The query is bottom-up from Erin. It returns Erin (isleaf 0), Bob (0), and Alice (1). Erin and Bob each have a parent row that satisfies the condition, so the walk continues. Alice has no manager, so no child row exists in this direction and she is the leaf. In a bottom-up query, CONNECTBY_ISLEAF = 1 identifies the top of the chain.