The village staff chart: WITH RECURSIVE down and up, each round rerun by a real SQLite; a cycle in the import, a guard, UNION vs UNION ALL. An interactive…
Why it matters
Hierarchies are everywhere: org charts, nested categories, comment threads, routes. A recursive CTE walks one in a single query. Three things often go wrong: the recursive part sees only the previous round’s rows, cyclic data makes it run forever, and UNION drops only rows that are exactly the same.
The key idea
The anchor once, then the same step repeated over the last round’s rows until nothing new comes
Common mistakes
Thinking the recursive member sees every row gathered so far The recursive part sees only the previous round’s rows (the working table), not the whole result. That is why each round moves just one step.
A WITH RECURSIVE query runs on and on The data has a cycle or there is no stopping condition. Add a guard column (WHERE b.level < n, or a path that refuses ids already passed). UNION helps only when the repeated rows are exactly the same.
The result rows are not in the expected order The order out of a recursive CTE depends on how the engine works and is not promised. Write ORDER BY in the outer query (say ORDER BY level).
Try it in this playground
Turn the walk upward Write the ON p.id = b.atasan_id: each round climbs to the boss.
Try UNION On shared bosses, a row exactly like another is dropped.
Stop the cycle with a guard In the import, put a condition on the recursive part until the query finishes.
Step through three rounds Pick the rounds one at a time: see what each one adds.