Sub topic 11
Handling cycles in the data
This chapter assumes you can already write a top-down query with START WITH, CONNECT BY PRIOR and LEVEL, and that you know what a self-referencing table is. Here you will see what happens when the parent-child links form a loop, how to get rows back anyway with NOCYCLE, and how to find the bad rows.
Why a hierarchy can loop
A tree has no loops. A self-referencing table does not enforce that. Nothing in a foreign key from manager_id to employee_id stops these situations:
- A row that is its own parent (
manager_id = employee_id). - Two rows that manage each other.
- A longer ring, such as A reports to D, D to C, C to B, and B to A.
Hand edits, bulk loads and application bugs all produce such rows. A hierarchical query follows the links one row at a time. If it reaches a row that is already an ancestor of the current row, it would walk the ring forever. Oracle detects this and stops with an error.
A small table with a loop
The examples use a five-row table so the loop is easy to see. The employees table from the earlier chapters is not changed.
CREATE TABLE org_cycle (
id NUMBER PRIMARY KEY,
name VARCHAR2(20),
manager_id NUMBER
);
INSERT INTO org_cycle VALUES (1, 'Ava', 4);
INSERT INTO org_cycle VALUES (2, 'Ben', 1);
INSERT INTO org_cycle VALUES (3, 'Cy', 2);
INSERT INTO org_cycle VALUES (4, 'Dee', 3);
INSERT INTO org_cycle VALUES (5, 'Eli', 3);
COMMIT;Ava reports to Dee, Ben to Ava, Cy to Ben, and Dee to Cy. That closes a ring of four. Eli reports to Cy and hangs off the ring.
The error: ORA-01436
Run a normal top-down query from Ava:
SELECT id, name, LEVEL
FROM org_cycle
START WITH id = 1
CONNECT BY PRIOR id = manager_id;Oracle fails with ORA-01436: CONNECT BY loop in user data. The walk goes Ava, Ben, Cy, Dee, and then Dee's child is Ava again. Ava is already an ancestor of Dee, so Oracle stops.
Two things about this error are easy to miss:
- It happens only if the traversal actually reaches the loop. A branch that never touches the ring runs without complaint, so bad data can sit unnoticed until someone starts from a different row.
- If every row in a ring has a manager, no row has
manager_id IS NULL. A query withSTART WITH manager_id IS NULLthen returns nothing and raises no error. A missing result can be a symptom of a cycle too.
NOCYCLE: return rows despite the loop
Put NOCYCLE right after CONNECT BY. Oracle then skips any child that is also an ancestor of the current row, instead of raising an error.
SELECT id, name, manager_id, LEVEL
FROM org_cycle
START WITH id = 1
CONNECT BY NOCYCLE PRIOR id = manager_id
ORDER SIBLINGS BY id;| ID | NAME | MANAGER_ID | LEVEL |
|---|---|---|---|
| 1 | Ava | 4 | 1 |
| 2 | Ben | 1 | 2 |
| 3 | Cy | 2 | 3 |
| 4 | Dee | 3 | 4 |
| 5 | Eli | 3 | 4 |
Each row appears once. Dee's child Ava is not returned a second time, because Ava is already on the path from the root to Dee. The loop is cut at the point where the walk would return to a row it has already visited.
NOCYCLE only changes what happens at the loop. The rest of the query behaves as before, and NOCYCLE does not repair the data.
CONNECT_BY_ISCYCLE: marking where the loop closes
With NOCYCLE in place, you no longer see where the data loops. The pseudocolumn CONNECT_BY_ISCYCLE shows it. For each returned row it is:
1if the row has a child that is also one of its ancestors.0otherwise.
SELECT id, name, LEVEL,
CONNECT_BY_ISCYCLE AS is_cycle
FROM org_cycle
START WITH id = 1
CONNECT BY NOCYCLE PRIOR id = manager_id
ORDER SIBLINGS BY id;| ID | NAME | LEVEL | IS_CYCLE |
|---|---|---|---|
| 1 | Ava | 1 | 0 |
| 2 | Ben | 2 | 0 |
| 3 | Cy | 3 | 0 |
| 4 | Dee | 4 | 1 |
| 5 | Eli | 4 | 0 |
Dee is flagged because Dee's child, Ava, is an ancestor of Dee. Cy and Eli are not flagged. Eli has no children at all, and Cy's children (Dee and Eli) are not ancestors.
CONNECT_BY_ISCYCLE is valid only together with NOCYCLE. If you use it without NOCYCLE, Oracle raises an error.
Printing the loop
Combine the flag with SYS_CONNECT_BY_PATH from the previous chapter to show the ring as text. Filtering with WHERE keeps only the flagged rows:
SELECT SYS_CONNECT_BY_PATH(name, ' -> ') AS loop_path
FROM org_cycle
WHERE CONNECT_BY_ISCYCLE = 1
START WITH id = 1
CONNECT BY NOCYCLE PRIOR id = manager_id;The result is one row:
-> Ava -> Ben -> Cy -> DeeThe path lists the rows from the root to the flagged row. The last name links back to the first one, which gives you the ring to fix. In a real table, run this with each suspect row as the start, or remove the START WITH clause so every row is tried as a root. The result will contain duplicates in that case, because the same ring is found from each of its members.
Self-references
A row whose manager_id equals its own id is a loop of length one. The standard START WITH manager_id IS NULL pattern never reaches it, because that row has a manager and is not a root. If you start from it, the query raises ORA-01436 unless NOCYCLE is present. With NOCYCLE, the row is returned once with CONNECT_BY_ISCYCLE = 1.
This also gives a cheap check for the worst kind of bad data:
SELECT id, name
FROM org_cycle
WHERE id = manager_id;Using NOCYCLE safely
NOCYCLE is a tool for reading data you do not fully control. Keep these points in mind.
- It hides the problem. A query that silently drops looping links can return numbers that look fine. A subtree total, for example, would count each row once, but the managers in the ring have no meaningful "top". Use
CONNECT_BY_ISCYCLEin a separate check query so the problem is reported somewhere. - Results depend on the starting row. The ring is cut just before the walk would return to its starting point. Starting from Ben instead of Ava puts the cut at a different place, so the returned shape differs. For a ring, no start row is the "correct" one.
- It does not remove the need for a root. Rings with no row above them are unreachable from
START WITH manager_id IS NULL. Those rows are missing from the output, with or withoutNOCYCLE. - Prevent it at the source. A foreign key cannot forbid cycles. Common safeguards are a trigger or application check that walks up from the new manager before accepting an update, and a regular check query like the ones above.
Recursive WITH and cycles
Recursive subquery factoring has its own cycle handling. It uses a separate CYCLE clause that marks the repeated row with a flag you name, instead of dropping it. The two approaches return slightly different rows for the same data. The comparison chapter covers that difference.
Summary of the tools
| Feature | What it does | Needs NOCYCLE |
|---|---|---|
| `CONNECT BY NOCYCLE` | Skips a child that is already an ancestor, so no error is raised | It is the keyword itself |
| `CONNECT_BY_ISCYCLE` | Returns 1 for a row whose child is also its ancestor | Yes |
| `WHERE id = manager_id` | Finds rows that are their own manager | No |
| `ORA-01436` | Reports that the walk met a loop | Occurs when NOCYCLE is absent |
Exercises
Exercise
A query uses START WITH managerid IS NULL and CONNECT BY PRIOR id = managerid. It runs without error, but a group of employees never appears in the output. They all report to one another in a ring. Why is there no ORA-01436, and how would you find them?
Show answer
The query starts only from rows with no manager and walks down from them. The ring is not reachable from any such row, so Oracle never meets the loop and raises no error. To find them, run a query with no START WITH (so every row is a root), use CONNECT BY NOCYCLE PRIOR id = managerid, and select the rows where CONNECTBYISCYCLE = 1. Adding SYSCONNECTBYPATH shows the ring.
Exercise
In the orgcycle table, you start from Ben (id = 2) with CONNECT BY NOCYCLE PRIOR id = managerid. Which row has CONNECTBYISCYCLE = 1?
Show answer
Ava (id = 1). The walk goes Ben, Cy, then Dee and Eli at level 3. Dee's child is Ava, who is not yet an ancestor, so Ava is returned at level 4. Ava's child is Ben, who is the root and therefore an ancestor, so Ava is flagged and Ben is not returned again.