SQL
Traverse Hierarchical Data with Recursive CTE
Query tree-like or hierarchical data structures (e.g., categories, comments, organizational charts) using a Common Table Expression (CTE) to traverse parent-child relationships.
WITH RECURSIVE CategoryPath AS (
SELECT id, name, parent_id, CAST(name AS VARCHAR(255)) AS path
FROM categories
WHERE parent_id IS NULL
UNION ALL
SELECT c.id, c.name, c.parent_id, CAST(cp.path || ' -> ' || c.name AS VARCHAR(255))
FROM categories c
JOIN CategoryPath cp ON c.parent_id = cp.id
)
SELECT id, name, parent_id, path FROM CategoryPath ORDER BY path;
How it works: This snippet uses a `WITH RECURSIVE` Common Table Expression (CTE) to traverse hierarchical data, such as a category tree. The 'anchor member' selects the root categories (those without a parent). The 'recursive member' then repeatedly joins back to the CTE to find children of the previously found categories, building a full path for each category. This is powerful for displaying nested data structures in web applications.