Course outline

SQLite / Intermediate: query structure and transactional design / Lesson 14

Traverse a hierarchy with recursive CTEs

Build bounded category traversal and reason about cycles and result ordering.

About 4 min readContent reviewed
On this page

Lesson goals

  • Explain anchor and recursive terms.
  • Apply a depth bound and track visited identifiers.
  • Separate traversal results from a guaranteed output order.

Represent the relationship

A category can have a parent category, giving a path from a broad group to a narrower one. A recursive common table expression starts with an anchor row and repeatedly derives further rows from those already found. Its scope is a single statement. Agree whether the task asks for descendants of one root, all roots, or paths through a graph before writing the query.

Traverse a disposable tree

Create this small fixture only in a new disposable SQLite database. The anchor chooses category 1 at depth zero. The recursive term finds children of the current row, increasing depth each time. The depth predicate supplies a bound for this example. The final ORDER BY determines display order; the order in which rows are discovered is not the result contract.

sql Walk children from one root
CREATE TABLE lab_category (id INTEGER PRIMARY KEY, parent_id INTEGER, name TEXT NOT NULL);
INSERT INTO lab_category VALUES (1, NULL, 'Supplies'), (2, 1, 'Paper'), (3, 2, 'Notebooks');
WITH RECURSIVE tree(id, name, depth) AS (
  SELECT id, name, 0 FROM lab_category WHERE id = 1
  UNION ALL
  SELECT c.id, c.name, tree.depth + 1
  FROM lab_category AS c JOIN tree ON c.parent_id = tree.id
  WHERE tree.depth < 5
)
SELECT id, name, depth FROM tree ORDER BY depth, id;

The fixture produces ids 1, 2, and 3 with depths 0, 1, and 2 respectively. These are derived from the declared rows, not measured runtime output. The bound includes depth five but does not prove that no deeper descendants exist.

Track a path as well as depth

A malformed parent relationship can contain a cycle. A depth limit prevents unbounded traversal but can still repeat nodes and hide the structural problem. The next query carries a slash-delimited identifier path and refuses a child already present on that path. Delimiters distinguish identifier 2 from 12. This representation is for integer identifiers in the fixture and is not a general escaping format for arbitrary text keys.

sql Stop revisiting a path
WITH RECURSIVE tree(id, path, depth) AS (
  SELECT id, printf('/%d/', id), 0 FROM lab_category WHERE id = 1
  UNION ALL
  SELECT c.id, tree.path || printf('%d/', c.id), tree.depth + 1
  FROM lab_category AS c JOIN tree ON c.parent_id = tree.id
  WHERE tree.depth < 5 AND instr(tree.path, printf('/%d/', c.id)) = 0
)
SELECT id, path, depth FROM tree ORDER BY depth, id;

Starting from id 1, the expected paths are /1/, /1/2/, and /1/2/3/. The path test prevents revisiting an identifier within the current path. It does not by itself validate every disconnected component or enforce a tree on future writes.

Understand the boundary

A depth cap is a safety and product decision, not evidence that all descendants were returned. A result at the maximum depth may have further children. A graph can also have multiple paths to a node; path-level cycle prevention does not globally deduplicate those paths. Define whether the desired result is nodes or paths and check the data model and constraints separately.

Verify expected and malformed data

Test a root without children, a missing root, a chain at the depth boundary, and a deliberately cyclic fixture. Compare returned identifiers and depths with a hand-drawn diagram. Include deterministic ordering for any user-facing output, and measure large hierarchies with representative indexes and data. Record whether truncated results need a warning or a separate continuation mechanism.

Common errors and fixes

Traversal repeats the same node.

Why it happens
A cycle exists and UNION ALL keeps producing another path.
How to fix it
Detect nodes already in the current path and retain a depth bound.
Prevent it next time
Validate hierarchy writes and test cycles in a disposable fixture.

A deeper category is missing from the result.

Why it happens
The depth cap excludes it.
How to fix it
Check whether the cap matches the requested business boundary.
Prevent it next time
Make truncation visible and test a chain crossing the limit.

Output appears in an unexpected order.

Why it happens
Discovery order was mistaken for a final ordering guarantee.
How to fix it
Use an explicit ORDER BY with a stable tie-breaker.
Prevent it next time
State and test the presentation order.

2 practice exercises

1. What depths are returned for the sample chain and why?

Show worked solution

The anchor returns id 1 at depth 0. Its child id 2 is depth 1, and id 3 is depth 2. There are no further matching children in the fixture, so recursion ends before the cap.

2. If a reachable child already appears in the current path, what does the second query do?

Show worked solution

The instr test finds the delimited identifier and excludes that recursive row. Other paths can still reach the same identifier, and disconnected cycles remain outside this root traversal.

Key takeaways

  • Anchor rows define starting points; recursive rows extend them.
  • Depth bounds and path checks serve different purposes.
  • Order final results explicitly and test truncation.

Official references