Walk a hierarchy such as categories or folders.
Section: CTEs and window functions
Use a recursive CTE
sql
sql
WITH RECURSIVE category_tree(id, name, parent_id, depth) AS (
SELECT id, name, parent_id, 0 FROM categories WHERE parent_id IS NULL
UNION ALL
SELECT c.id, c.name, c.parent_id, ct.depth + 1
FROM categories c
JOIN category_tree ct ON c.parent_id = ct.id
)
SELECT * FROM category_tree;Explanation
Recursive CTEs are the go-to pattern for tree traversal in SQLite.
Learn the surrounding workflow
Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.
Related commands
Same sheet · prioritizing CTEs and window functions