Databases & SQL Master Course — 049. Hierarchy Cycles and Path Safety
Lesson 049 Hierarchy Cycles and Path Safety
A recursive traversal can revisit a node through a cycle or reach it along several different paths. Those are different situations. This lesson uses a tiny cyclic graph to show path-local cycle guards, unique-node reachability, and why adding depth to a UNION result can defeat naive duplicate-based termination.
Prerequisites and objectives
Complete Lesson 048. You should understand recursive anchors, UNION and UNION ALL, string concatenation, and depth limits. You will prevent revisiting a node on one path, identify cycle-closing edges, distinguish node and path results, and bound every diagnostic traversal safely.
Step 1 Inspect the graph before traversing
Run the setup once in an empty SQLite practice database. Each row is one directed edge. The edge 3 to 1 closes a cycle through 1, 2, and 3. The edge 4 to 4 is a self-loop. Node 4 can be reached directly from 2 or through 3.
CREATE TABLE edges (
source_id INTEGER NOT NULL,
target_id INTEGER NOT NULL,
PRIMARY KEY (source_id, target_id)
);
INSERT INTO edges VALUES (1,2),(2,3),(3,1),(2,4),(4,4),(3,4);
The graph has four reachable node identities from anchor 1, but more than four simple paths ending at those nodes. Our goal must say whether it wants unique nodes, paths, or cycle evidence. There is no single duplicate-removal rule that automatically answers all three questions.
Step 2 Track visited nodes within a path
The path string uses slash-delimited integer IDs. Before extending a path, check whether the next target already appears as a complete delimited token.
WITH RECURSIVE paths(node_id, path, depth) AS (
SELECT 1, '/1/', 0
UNION ALL
SELECT e.target_id, p.path || e.target_id || '/', p.depth + 1
FROM paths AS p INNER JOIN edges AS e ON e.source_id = p.node_id
WHERE p.depth < 10 AND instr(p.path, '/' || e.target_id || '/') = 0
)
SELECT node_id, path, depth FROM paths ORDER BY depth, path;
The traversal returns five path states. Node 4 appears twice because two different nonrepeating paths reach it. The guard rejects 3 to 1 on the current path and rejects the 4 self-loop. A depth bound of ten is retained as an additional safeguard.
Delimiters matter: searching for bare 1 would also find it inside 11. The token /1/ avoids that ambiguity for this integer-ID encoding. Arbitrary text identifiers would require a suitable unambiguous encoding rather than copying this shortcut blindly.
Step 3 Interpret the guard’s scope
The visited check is local to one path. It prevents a node from repeating within that path, but it does not globally suppress a node reached by another route. That is correct when distinct paths are useful evidence. It can be unnecessary work when the task only asks which nodes are reachable.
Even a cycle-safe simple-path query can produce many paths in a dense graph. Avoid interpreting a depth guard and a visited string as a guarantee of small resource use. For unfamiliar data, inspect its size, use deliberate limits, and choose the narrowest state representation needed by the question.
Step 4 Find cycle-closing edges
The safe path states can also expose edges whose target is already in that path. These are rejected extensions, not additional traversal rows.
WITH RECURSIVE paths(node_id, path, depth) AS (
SELECT 1, '/1/', 0
UNION ALL
SELECT e.target_id, p.path || e.target_id || '/', p.depth + 1
FROM paths AS p INNER JOIN edges AS e ON e.source_id = p.node_id
WHERE p.depth < 10 AND instr(p.path, '/' || e.target_id || '/') = 0
)
SELECT p.path, e.source_id, e.target_id
FROM paths AS p INNER JOIN edges AS e ON e.source_id = p.node_id
WHERE instr(p.path, '/' || e.target_id || '/') > 0
ORDER BY p.path, e.target_id;
There are three path-specific cycle warnings: one return from 3 to 1 and two encounters with the self-loop at 4 along different paths. This does not mean there are three distinct stored cyclic edges; the underlying self-loop is one edge encountered twice.

Step 5 Compute unique-node reachability
If only node identities matter, carry just node_id and use UNION to suppress repeated states.
WITH RECURSIVE reachable(node_id) AS (
SELECT 1
UNION
SELECT e.target_id FROM edges AS e INNER JOIN reachable AS r ON e.source_id = r.node_id
)
SELECT node_id FROM reachable ORDER BY node_id;
With this finite four-node graph and an ID-only state, repeated node rows are discarded, so cycles do not create an endless stream of new states. The result loses path and depth information intentionally. That is a suitable tradeoff for a reachability set, not for a path report.
Step 6 See why depth changes duplicate identity
If the recursive row contains both node_id and depth, revisiting node 1 at depth three differs from node 1 at depth zero. UNION compares the complete row, so it no longer removes those revisits merely because the node ID repeats.
Never test that assumption with an unbounded cyclic query. A small explicit depth limit can reveal the behavior safely. The lesson’s verification checks a depth-four version and confirms repeated IDs at different depths. The stopping condition comes from the bound, not from a mistaken belief that UNION deduplicates only the first column.
Practice with worked solutions
Exercise 1
Return distinct reachable node IDs from the already cycle-safe path relation.
Worked solution
WITH RECURSIVE paths(node_id, path, depth) AS (
SELECT 1, '/1/', 0
UNION ALL
SELECT e.target_id, p.path || e.target_id || '/', p.depth + 1
FROM paths AS p INNER JOIN edges AS e ON e.source_id = p.node_id
WHERE p.depth < 10 AND instr(p.path, '/' || e.target_id || '/') = 0
)
SELECT DISTINCT node_id FROM paths ORDER BY node_id;
The four identities agree with the ID-only reachability query. This projection discards the fact that node 4 had two distinct safe paths.
Exercise 2
List the two safe paths that end at node 4.
Worked solution
WITH RECURSIVE paths(node_id, path, depth) AS (
SELECT 1, '/1/', 0
UNION ALL
SELECT e.target_id, p.path || e.target_id || '/', p.depth + 1
FROM paths AS p INNER JOIN edges AS e ON e.source_id = p.node_id
WHERE p.depth < 10 AND instr(p.path, '/' || e.target_id || '/') = 0
)
SELECT path, depth FROM paths WHERE node_id = 4 ORDER BY depth, path;
The direct route through 2 has depth two; the route through 2 and 3 has depth three. Neither path repeats a node, despite ending at the same destination.
Exercise 3
Safely demonstrate repeated node IDs when UNION compares node and depth together.
Worked solution
WITH RECURSIVE steps(node_id, depth) AS (
SELECT 1, 0
UNION
SELECT e.target_id, s.depth + 1 FROM steps AS s
INNER JOIN edges AS e ON e.source_id = s.node_id
WHERE s.depth < 4
)
SELECT node_id, depth FROM steps ORDER BY depth, node_id;
Eight distinct node-depth states appear. Node 1 repeats at another depth, so UNION alone would not provide the intended node-only cycle protection. The explicit depth bound keeps this diagnostic finite.
Exercise 4
Count safe path states and distinct reachable nodes side by side.
Worked solution
WITH RECURSIVE paths(node_id, path, depth) AS (
SELECT 1, '/1/', 0
UNION ALL
SELECT e.target_id, p.path || e.target_id || '/', p.depth + 1
FROM paths AS p INNER JOIN edges AS e ON e.source_id = p.node_id
WHERE p.depth < 10 AND instr(p.path, '/' || e.target_id || '/') = 0
)
SELECT COUNT(*) AS path_states, COUNT(DISTINCT node_id) AS reachable_nodes FROM paths;
Five path states describe four node identities. Naming both counts prevents a path count from being mistaken for the size of the reachable node set.
Knowledge check
Question 1
What does the path-local visited guard prevent?
- All alternative routes globally
- All branching
- Every duplicate output value
- A node repeating within the current path
Answer and explanation
D. It checks membership in that path’s accumulated token sequence.
Question 2
Why use delimiters around integer IDs?
- To remove the need for a cycle guard
- To make the path a numeric rather than text value
- To avoid confusing 1 with part of 11
- To make the path check globally deduplicate nodes
Answer and explanation
C. Whole-token matching needs an unambiguous representation.
Question 3
Why can UNION fail to stop revisits when depth is included?
- The complete node-depth rows remain different
- UNION compares only the first selected column
- UNION becomes UNION ALL
- Including depth disables the recursive term
Answer and explanation
A. Duplicate elimination compares all selected state columns.
Question 4
How many unique nodes are reachable from 1?
- Six
- Eight
- Five
- Four
Answer and explanation
D. The reachable identities are 1, 2, 3, and 4.
Question 5
Does cycle-safe path enumeration guarantee a small result?
- Yes, if every path is free of repeated nodes
- No
- Yes, when the maximum depth is fixed
- Always
Answer and explanation
B. Many distinct paths can exist even when no path repeats a node.
Pitfalls and summary
Do not confuse path-local safety with global deduplication or assume UNION ignores depth and path columns. Choose a state that matches the question, encode visited identities unambiguously, and retain explicit safety bounds where appropriate. Test cycles only with controlled finite diagnostics.
SQLite behavior and references
Examples were checked with SQLite 3.53.1 on 10 October 2026. Use a SQLite SQL editor; Python is not a prerequisite. Verify dialect-specific functions, comparison rules, and numeric behavior before moving the examples to another engine.
Primary references
- SQLite recursive WITH: Recursive state, UNION duplicate suppression, and bounded traversal.
- SQLite core functions: instr for the deliberately delimited path test.
- SQLite SELECT: Whole-row distinct comparison and result ordering.