Recursive CTEs
WITH RECURSIVE lets a CTE reference itself, enabling loops in SQL.
Generate numbers 1 through 10:
How it works:
- Base case:
SELECT1ASn (the starting point) - Recursive step:
SELECTn + 1FROMnumsWHEREn < 10 - Stops when the
WHEREcondition is false
Real-world uses:
- Traversing org chart hierarchies
- Bill of materials (parts within parts)
- Generating date series
Check your understanding
What are recursive CTEs used for?
Examples run on the employees sample database. Open any of them in the playground to experiment.