Databases & SQL Master Course — 048. Recursive CTE Fundamentals
Lesson 048 Recursive CTE Fundamentals
A fixed number of self joins can follow a fixed number of hierarchy levels. A recursive CTE can repeatedly follow a relationship until no more qualifying rows remain. This lesson introduces the anchor, recursive step, and stopping rule using a small category tree with an explicit depth bound.
Prerequisites and objectives
Complete Lesson 047. You should understand self joins, ordinary CTEs, UNION ALL, and keys. You will trace recursive expansion, report depth, choose a starting node, and distinguish a logical stopping condition from an assumption that every input is a valid tree.
Step 1 Define the hierarchy
Run this fixture once in a fresh empty SQLite practice database. Each row is a fictional category. parent_id points to its direct parent, while NULL marks a root. Catalog and Archive are separate roots; only the Catalog tree is used in the first traversal.
PRAGMA foreign_keys = ON;
CREATE TABLE categories (
category_id INTEGER PRIMARY KEY,
category_name TEXT NOT NULL,
parent_id INTEGER REFERENCES categories(category_id)
);
INSERT INTO categories VALUES
(1,'Catalog',NULL),(2,'Books',1),(3,'Supplies',1),
(4,'Travel Books',2),(5,'Technical Books',2),
(6,'Paper',3),(7,'Pens',3),(8,'Archive',NULL);
Catalog has children Books and Supplies. Books has Travel Books and Technical Books. Supplies has Paper and Pens. The requested result includes Catalog itself plus every reachable descendant in this small tree, along with its distance from Catalog in parent-child steps.
Step 2 Identify the anchor
The anchor is the nonrecursive SELECT that starts the result. Here it selects category 1 and assigns depth zero. The recursive step then finds children whose parent_id equals a category already reached and increments depth by one.
WITH RECURSIVE subtree(category_id, category_name, depth) AS (
SELECT category_id, category_name, 0 FROM categories WHERE category_id = 1
UNION ALL
SELECT child.category_id, child.category_name, parent.depth + 1
FROM categories AS child INNER JOIN subtree AS parent ON child.parent_id = parent.category_id
WHERE parent.depth < 10
)
SELECT category_id, category_name, depth FROM subtree ORDER BY depth, category_id;
The result has seven rows. Catalog is at depth zero, its two children at depth one, and the four grandchildren at depth two. Archive does not appear because no parent-child path from Catalog reaches it.

Step 3 Read the recursive boundary
WITH RECURSIVE introduces the recursive form. The CTE’s named columns describe the rows carried through the expansion. UNION ALL combines the anchor rows and newly found child rows while preserving occurrences. The recursive SELECT refers to subtree as parent, making the previous results available for the next relationship step.
SQLite documents restrictions on recursive SELECTs, including limits on where the recursive reference appears and on aggregate or window functions within that recursive term. These examples use one direct reference and a simple join. Do not assume every ordinary SELECT can be pasted unchanged into a recursive step.
Step 4 Understand termination
In this acyclic fixture, leaf categories have no children, so expansion naturally stops. The condition parent.depth < 10 also prevents generating nodes deeper than ten edges from the anchor. It is an explicit defensive bound for the practice query.
A depth limit bounds path length, not necessarily total row count. A highly branching graph can still produce many rows at shallow depth. Keep the practice dataset small and understand its shape before scaling. The next lesson addresses cycles and repeated paths directly.
Step 5 Keep traversal order separate from presentation
The final ORDER BY depth, category_id gives a reproducible displayed sequence. Do not infer that the database must physically visit nodes in that same order. Recursive work scheduling and final output ordering are separate concerns.
The depth value is relative to the selected anchor. Starting from Books makes Books depth zero and its children depth one, even though Books is one level below Catalog in the larger hierarchy. Name the starting point when presenting depth to a reader.
Step 6 Test boundary anchors
An anchor selecting no row leads to an empty traversal because there is no initial node to expand. A leaf anchor returns only itself. A maximum depth of one includes the starting node and direct children but deliberately excludes grandchildren.
These tests reveal whether a query includes its root, how it interprets depth, and whether its limit applies before or after the next step is generated. Do not treat those choices as cosmetic; they affect the report’s membership.
Step 7 Separate referential integrity from tree validity
The foreign key ensures referenced parent IDs exist when enforcement is enabled. It does not by itself prevent a category from referencing itself or forming a longer cycle. The current data was chosen as an acyclic tree, but that property must be validated or enforced by additional design in a real application.
Likewise, a graph can have several paths to the same destination even without a cycle. UNION ALL preserves paths as rows unless the query deliberately deduplicates an appropriate state. Think about whether the answer needs nodes, paths, or repeated occurrences before choosing a recursive representation.
Practice with worked solutions
Exercise 1
Traverse the Books subtree with depth measured from Books.
Worked solution
WITH RECURSIVE subtree(category_id, category_name, depth) AS (
SELECT category_id, category_name, 0 FROM categories WHERE category_id = 2
UNION ALL
SELECT child.category_id, child.category_name, parent.depth + 1
FROM categories AS child INNER JOIN subtree AS parent ON child.parent_id = parent.category_id
WHERE parent.depth < 10
)
SELECT category_id, category_name, depth FROM subtree ORDER BY depth, category_id;
Books becomes depth zero, with its two children at depth one. Catalog is an ancestor, not a descendant, so it is not included in this direction of traversal.
Exercise 2
Limit the Catalog traversal to direct children and the root.
Worked solution
WITH RECURSIVE subtree(category_id, category_name, depth) AS (
SELECT category_id, category_name, 0 FROM categories WHERE category_id = 1
UNION ALL
SELECT child.category_id, child.category_name, parent.depth + 1
FROM categories AS child INNER JOIN subtree AS parent ON child.parent_id = parent.category_id
WHERE parent.depth < 1
)
SELECT category_id, depth FROM subtree ORDER BY depth, category_id;
The recursive step expands only parents whose depth is below one. It therefore creates depth-one children but does not expand those children into grandchildren.
Exercise 3
Use a missing anchor ID and predict the result.
Worked solution
WITH RECURSIVE subtree(category_id, category_name, depth) AS (
SELECT category_id, category_name, 0 FROM categories WHERE category_id = 999
UNION ALL
SELECT child.category_id, child.category_name, parent.depth + 1
FROM categories AS child INNER JOIN subtree AS parent ON child.parent_id = parent.category_id
WHERE parent.depth < 10
)
SELECT category_id FROM subtree ORDER BY category_id;
No anchor row exists, so no recursive row can be generated. The empty result differs from a root with no children, which would still return its own anchor row.
Exercise 4
Count Catalog descendants while excluding Catalog itself.
Worked solution
WITH RECURSIVE subtree(category_id, category_name, depth) AS (
SELECT category_id, category_name, 0 FROM categories WHERE category_id = 1
UNION ALL
SELECT child.category_id, child.category_name, parent.depth + 1
FROM categories AS child INNER JOIN subtree AS parent ON child.parent_id = parent.category_id
WHERE parent.depth < 10
)
SELECT COUNT(*) AS descendants FROM subtree WHERE depth > 0;
There are six descendants. The full traversal has seven rows because it includes the root; the final filter removes only depth zero.
Knowledge check
Question 1
What starts a recursive CTE?
- The final ORDER BY
- The anchor query
- An automatic full-table copy
- A GROUP BY requirement
Answer and explanation
B. The anchor supplies the initial rows from which expansion begins.
Question 2
What does depth zero mean here?
- Every leaf
- A missing category
- The global root in every query
- The selected starting node
Answer and explanation
D. Depth is relative to the chosen anchor.
Question 3
Does a depth bound alone guarantee a tiny result?
- No
- Always
- Yes, if UNION ALL is used
- Yes, if the maximum depth is less than ten
Answer and explanation
A. Many branches can generate many rows within a shallow maximum depth.
Question 4
Why is Archive absent from the Catalog traversal?
- Its ID is too large
- NULL roots are deleted
- It is not reachable from Catalog through child links
- The table is sorted incorrectly
Answer and explanation
C. The anchor and relationship direction define reachability.
Question 5
Does a parent foreign key prove the graph is acyclic?
- No
- Yes, if every non-NULL parent exists
- Yes
- Yes, if every node has at most one parent
Answer and explanation
A. Reference existence and cycle prevention are different rules.
Pitfalls and summary
Define the anchor, recursive relationship, result grain, and stopping policy before execution. Test leaves, missing anchors, and depth boundaries. Recursive CTEs express repeated traversal clearly, but their safety and meaning depend on the data shape and the state carried between steps.
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: Anchor and recursive terms, restrictions, and termination controls.
- SQLite foreign keys: Parent-reference integrity.
- SQLite SELECT: Final ordering and filtering of recursive results.