DEV Community

Discussion on: How to write SQL recursive CTE in 5 steps

Collapse
 
geraldew profile image
geraldew

Always good to see articles describing how recursive queries work - disclaimer, I've also written one here on Dev (but it wasn't intended as an introduction to the concept).

With recursion, there's always a need to be sure that the looping will end. I'm not seeing anything here to be certain of that - other than it being known to be true for the example data. There are various possible solutions (I have a my own preferred method) so maybe that would make a good follow-up piece.

Collapse
 
franckpachot profile image
Franck Pachot YugabyteDB • Edited

The declaration appears recursive, but it is executed iteratively rather than recursively. The condition to stop recursion would be when mgr is null but here it is the beginning of the iteration. You see KING first in the result. The loop concludes when there are no rows at the next level. This depends on the data, not the condition.

Collapse
 
alfiqmiq profile image
Marek • Edited

Always good to include hints in query (example for MySQL):
WITH
...
SELECT /*+MAX_EXECUTION_TIME(1000) SET_VAR(CTE_MAX_RECURSION_DEPTH=100)*/
...