SQLite Recursive CTEs: Reachability, Paths and Cycle Guards
Write SQLite recursive CTEs that handle cycles correctly. Compare unique reachability with path traversal, understand UNION with depth, and run a tested Python lab.
A recursive CTE can find reachable nodes or enumerate paths, but those are different results. In SQLite, UNION can stop repeated node IDs when the recursive row contains only that identity. Adding changing depth or path columns changes duplicate detection. For path output, track visited IDs within each path and apply a deliberate depth bound. The runnable lab below demonstrates both approaches on invented directed graphs.
Choose whether a row represents a node or a path
A category browser asks which items are below a category. A dependency report asks how a component is reached. Both follow edges, yet one needs each reachable node once and the other may need several paths to the same node. Choosing the wrong row identity causes either missing explanations or repeated results.
Our fixture has a diamond: 1 leads to 2 and 3, and both lead to 4. It also contains a cycle between 2 and 4, a self-loop at 5, a return edge from 11 to 1, and isolated node 6. These features deliberately break assumptions that would be invisible in a clean tree.
For root 1, unique reachability returns 1, 2, 3, 4, 5 and 11. The guarded path query returns nine path prefixes because a node may occur through more than one route. These counts are different by design. Removing duplicates from the final display would hide the distinction instead of resolving it.
Anchor an existing node, then follow the intended edge direction
The nonrecursive part selects an existing root from node. The recursive part joins the current node to edge.src and emits edge.dst. This follows outgoing edges. If the stored relationship means child-to-parent rather than parent-to-child, review that direction before interpreting a result as descendants.
Selecting the anchor from node also defines missing-root behavior: root 99 produces no initial row and therefore no traversal. Starting with SELECT :root instead would seed that number even when no corresponding node exists. Neither pattern is universally correct; the fixture intentionally requires an existing root.
All runtime values use bound parameters. The schema separates nodes from directed edges and makes each source-destination pair unique. Enforced foreign keys require real endpoint rows, but they do not prohibit a cycle or a self-loop. Those are separate graph rules.
The root is depth zero in this article. A direct neighbor has depth one. Keep that convention visible when an API exposes a maximum depth, since a limit of zero here means the existing root only rather than an empty result.
UNION works for unique reachability when identity stays stable
The REACH query projects a single id column throughout recursion. When a cycle leads back to a previously generated ID, the UNION duplicate rule discards that row. Because this fixture has finitely many node IDs and follows only stored edges, there are only finitely many distinct recursive rows.
That reasoning depends on the complete row shape. The deliberately wrong query uses walk(id, depth). Visiting node 2 at depth 1 and again at depth 3 produces different rows. UNION does not compare just the first column, so increasing depth supplies endlessly new rows around a reachable cycle.
The lab runs that wrong query only behind a progress-handler instruction budget and expects an interruption. Do not copy the BAD query into an unguarded production console. Its purpose is to make the failure observable without allowing the demonstration to run indefinitely.
Source: SQLite WITH clause: recursive rows, UNION and queue behavior ↗
Use a path-local visited set when routes matter
The PATHS query keeps id, depth and seen. A path starts as /1/. Before following an edge to destination 4, it looks for the token /4/ in seen. If absent, the recursive step appends 4/; if present, that edge would revisit a node within this path and is skipped.
The delimiters matter. Searching for the bare text 1 inside /11/ would report a false match. The fixture verifies that traversal from 11 to 1 is allowed by searching for /1/ instead. This representation is safe for the lab’s integer node IDs because their printed form contains no slash.
Do not apply the same string representation to arbitrary text identifiers that may contain the delimiter. Use an unambiguous representation suited to your data and database. The important rule is membership in the current path, not the particular punctuation used in this example.
Path-local membership permits two different routes to node 4 through the diamond. It stops a repeated node within either route without treating a visit in one branch as a global ban on all other branches. That is why UNION ALL is appropriate for this guarded path enumeration.
A depth bound limits output; it does not prove completeness
The recursive predicate w.depth < :max_depth permits a child at exactly max_depth but does not expand that child further. With a cap of 2, the fixture omits node 5 even though the unique-reachability query proves that 5 is reachable. A bounded result must be described as bounded.
The Python wrapper accepts integer caps from 0 through 20 and rejects booleans, fractions and values outside that interval. This is an application limit chosen for the teaching function. It is not a statement about SQLite’s maximum supported recursive depth.
Cycle guards do not prevent path explosion in a graph with many branching and merging routes. Even a finite set of simple paths can be large. Choose unique reachability when that answers the question, and define additional operational limits when path output is necessary.
The progress handler is a separate execution guard measured in SQLite virtual-machine instructions, not a wall-clock timeout. The test removes it in finally and verifies that the connection can execute another statement. Do not treat the fixture’s instruction count as a suitable production budget.
Source: Python sqlite3: progress-handler instruction callbacks ↗
Run the complete SQLite and Python lab
Save this script as recursive_cte.py and run python recursive_cte.py with Python 3.12 or later and its sqlite3 module. It creates only an in-memory database. The exact published script passed 738 checks on Python 3.12.14 with SQLite 3.53.1 in the authoring environment.
The first fixture checks duplicate node visits, multiple routes, a self-loop, an isolated root, a missing root, depth boundaries and the delimiter case. It then interrupts the intentionally unsafe query, clears the handler, and confirms that ordinary queries still work.
The remaining checks compare SQL results against independent Python breadth-first reachability and depth-first simple-path enumeration. Sixty seeded six-node graphs are tested with three roots and three depth caps. The oracle carries a Python list of visited IDs rather than reproducing the SQL string-membership expression.
"""Python 3.12+; invented in-memory directed graphs; SQLite-specific SQL."""
from collections import deque
import platform
import random
import sqlite3
REACH = '''
WITH RECURSIVE reached(id) AS (
SELECT id FROM node WHERE id = :root
UNION
SELECT e.dst FROM edge AS e JOIN reached AS r ON e.src = r.id
)
SELECT id FROM reached ORDER BY id;
'''
PATHS = '''
WITH RECURSIVE walk(id, depth, seen) AS (
SELECT id, 0, '/' || id || '/' FROM node WHERE id = :root
UNION ALL
SELECT e.dst, w.depth + 1, w.seen || e.dst || '/'
FROM edge AS e JOIN walk AS w ON e.src = w.id
WHERE w.depth < :max_depth
AND instr(w.seen, '/' || e.dst || '/') = 0
)
SELECT id, depth, seen FROM walk ORDER BY depth, id, seen;
'''
# Deliberately wrong: UNION deduplicates (id, depth), not id alone.
BAD = '''
WITH RECURSIVE walk(id, depth) AS (
SELECT id, 0 FROM node WHERE id = :root
UNION
SELECT e.dst, w.depth + 1 FROM edge AS e JOIN walk AS w ON e.src = w.id
)
SELECT count(*) FROM walk;
'''
checks = 0
def check(condition, label):
global checks
checks += 1
if not condition:
raise AssertionError(label)
def load(con, ids, edges):
con.execute('DELETE FROM edge')
con.execute('DELETE FROM node')
con.executemany('INSERT INTO node VALUES(?)', [(x,) for x in ids])
con.executemany('INSERT INTO edge VALUES(?,?)', edges)
def paths(con, root, cap):
if type(cap) is not int or not 0 <= cap <= 20:
raise ValueError('Use an integer max_depth from 0 to 20')
return con.execute(PATHS, {'root': root, 'max_depth': cap}).fetchall()
def oracle(ids, edges, root, cap):
if root not in ids:
return []
adjacency = {x: [] for x in ids}
for src, dst in edges:
adjacency[src].append(dst)
result = []
def visit(path):
result.append((path[-1], len(path)-1, '/'+'/'.join(map(str,path))+'/'))
if len(path)-1 < cap:
for dst in adjacency[path[-1]]:
if dst not in path:
visit(path+[dst])
visit([root])
return sorted(result, key=lambda x:(x[1],x[0],x[2]))
def reachable(ids, edges, root):
if root not in ids:
return []
found = {root}
queue = deque([root])
while queue:
src = queue.popleft()
for a, b in edges:
if a == src and b not in found:
found.add(b)
queue.append(b)
return sorted(found)
def main():
with sqlite3.connect(':memory:') as con:
con.execute('PRAGMA foreign_keys=ON')
con.executescript('''
CREATE TABLE node(id INTEGER PRIMARY KEY);
CREATE TABLE edge(
src INTEGER NOT NULL REFERENCES node(id),
dst INTEGER NOT NULL REFERENCES node(id),
PRIMARY KEY(src,dst)
);
''')
ids = [1,2,3,4,5,6,11]
edges = [(1,2),(1,3),(2,4),(3,4),(4,2),(4,5),(5,5),(1,11),(11,1)]
load(con, ids, edges)
found = [x[0] for x in con.execute(REACH, {'root':1})]
check(found == [1,2,3,4,5,11], 'unique reachability with cycles')
rows = paths(con,1,10)
check(rows == oracle(ids,edges,1,10), 'path rows match independent DFS')
check(len(rows) == 9, 'nine simple path prefixes')
check(sum(x[0] == 4 for x in rows) == 2, 'diamond keeps two paths to node 4')
check(all(len(x[2].strip('/').split('/')) == len(set(x[2].strip('/').split('/')))
for x in rows), 'no node repeats within a path')
check(paths(con,1,0) == [(1,0,'/1/')], 'depth zero includes only root')
capped = paths(con,1,2)
check(all(x[1] <= 2 for x in capped), 'depth boundary enforced')
check(5 not in {x[0] for x in capped}, 'depth cap can omit reachable nodes')
check((1,1,'/11/1/') in paths(con,11,2), 'integer delimiter avoids 1 versus 11 collision')
check(paths(con,6,10) == [(6,0,'/6/')], 'isolated existing root')
check(paths(con,99,10) == [], 'missing root has no anchor')
check(list(con.execute(REACH, {'root':99})) == [], 'missing reachability root')
for cap in [-1,21,True,1.5]:
try:
paths(con,1,cap)
except ValueError:
check(True, 'invalid depth rejected')
else:
raise AssertionError('Expected depth validation')
calls = 0
def stop_bad_query():
nonlocal calls
calls += 1
return calls >= 100
con.set_progress_handler(stop_bad_query,100)
try:
con.execute(BAD, {'root':1}).fetchall()
except sqlite3.OperationalError as error:
check(calls >= 100 and 'interrupt' in str(error).lower(),
'changing depth defeats UNION; instruction budget interrupts')
else:
raise AssertionError('Expected guarded nontermination')
finally:
con.set_progress_handler(None,0)
check(con.execute('SELECT 1').fetchone() == (1,), 'handler cleared after interruption')
rng = random.Random(85)
for _ in range(60):
ids = list(range(1,7))
edges = [(a,b) for a in ids for b in ids if rng.random() < .22]
load(con,ids,edges)
for root in [1,3,6]:
actual = [x[0] for x in con.execute(REACH, {'root':root})]
check(actual == reachable(ids,edges,root), 'BFS reachability oracle')
for cap in [0,2,5]:
check(paths(con,root,cap) == oracle(ids,edges,root,cap),
'DFS path/depth oracle')
print(f'PASS: {checks} checks; 60 seeded graphs; Python {platform.python_version()}; SQLite {sqlite3.sqlite_version}')
if __name__ == '__main__':
main()
Interpret nodes, path prefixes and ordering separately
The final output should begin PASS: 738 checks; 60 seeded graphs. Python and SQLite version strings identify the runtime used. The deterministic seed makes the generated graph cases reproducible; these cases are not an exhaustive proof for every graph or a performance benchmark.
For the hand-written graph, two rows ending at 4 are expected because their seen values represent different routes. Node 2 can also appear after travelling through 3 and 4, even though it was visited earlier in another branch. The guard prohibits repeating it inside the same path, not appearing anywhere else in the output.
The path query explicitly orders its final rows by depth, ID and seen. That defines presentation order without claiming a particular internal queue order. Sorting path text also does not turn integer IDs into numeric sequences; /1/11/ and /1/2/ have ordinary text ordering.
A row at an intermediate node is a path prefix, not necessarily a route to a leaf. If the report needs only paths to a selected destination or terminal nodes, define that output requirement separately. Filtering the final output and preventing recursive expansion solve different problems.
Use the smallest traversal state that answers the question
For a list of affected components, unique reachability often gives the required node set without storing every route. Join that completed ID result to descriptive attributes afterward when those attributes are not part of traversal identity. This keeps the deduplication reasoning easy to inspect.
For route explanations, retain the path and disclose the depth boundary. If a consumer wants a minimum depth for each node, it may aggregate the bounded path output, but a cap that excludes relevant routes limits what that answer establishes. Do not label an arbitrary bounded route search a general shortest-path algorithm.
For a strictly enforced tree, a simpler UNION ALL traversal may suffice, yet the tree invariant must be established outside a convenient example. Referential integrity alone allows the cyclic edge fixture here. If imports or edits can violate the invariant, test that failure before relying on tree-only reasoning.
The related UNION comparison guide explains duplicate handling outside recursion. The foreign-key guide explains how connection settings affect endpoint integrity. Together they help distinguish row-set semantics, graph structure and storage constraints.
| Desired answer | Recursive row state | Main caution |
|---|---|---|
| Each reachable node once | Stable node ID with UNION | Adding changing columns alters duplicate identity |
| Different simple routes | ID, depth and path with a visited guard | Multiple paths can grow rapidly |
| A bounded exploration | Explicit maximum depth | Results may omit reachable nodes |
| A tree-only traversal | UNION ALL under a verified tree invariant | Foreign keys alone do not establish that invariant |
Make termination part of the query’s explanation
A recursive query should explain why another step eventually stops. In the reachability query, the finite node identity and UNION duplicate rule provide that argument. In the path query, the visited membership check prevents a repeated node in a route, and the depth predicate imposes an additional application boundary.
Before using a new traversal, test a diamond, a cycle, a self-loop, a missing root and an isolated node. State whether output rows represent nodes or paths and whether the result is complete or capped. Those decisions make recursive SQL much easier to review than a query that merely appears to work on a tree.
Your next steps
- Decide whether the result represents unique nodes or distinct routes before choosing recursive state.
- UNION deduplicates complete rows; changing depth can defeat a node-level cycle assumption.
- A path-local visited guard prevents repeated IDs within a route while preserving alternate routes.
- Depth caps can omit reachable nodes; label bounded results accordingly.
- Use independent graph fixtures and operational execution guards rather than assuming every input is a tree.
Sources & official resources
Linked resources checked on 2026-11-02. Technical behavior and provider guidance can change; check the documentation for the version you use.
About this guide and its recommendations
Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.
Suggest a correction →