SQL/Subqueries & CTEs 9 min

Recursive CTEs

Generate sequences and walk hierarchies.

recursiveseriesdate spine

A recursive CTE has an anchor query, then a query that refers back to the CTE itself, run repeatedly until it returns nothing. The simplest use is generating a series of numbers.

sql · editable
loading editor…

Try it: Stop at 5 and show the cube instead.

The most useful version is a date spine: a complete calendar you LEFT JOIN your data onto, so days with no activity still appear as zeros instead of vanishing.

sql · editable
loading editor…

Always give the recursion a stopping condition. Without one it runs until the engine kills it.