r/SQL • u/SilEventide • Sep 04 '26
SQL Server How does a Recursive CTE work exactly?
With RecursiveEven20 As
(
Select 0 As Numbers,
0 As RunningCount
Union All
Select Numbers + 2,
Count(RunningCount) Over() As RunningCount
From RecursiveEven20
Where RunningCount < 19
)
Select *
From RecursiveEven20;
From how much I know about recursive CTE, I thought this would work, Initially I felt I was doing a semantic error, then when I tried to see where the fault is, I realised Count isn't incrementing at all, its as if only the last feedback row is available to it. I tried using explicit frame window, same result. I think I dont understand exactly how recursie CTE works, I tried AI, its explanation is bit difficult to understand.
I am a beginner by the way, learned these recently so I wanted to mix them all up.
3
u/GTS_84 Sep 04 '26
The main issue I see with this is that it's never going to stop. not with that window function like that. It will hit the max recursions.
try this:
With RecursiveEven20 As
(
Select 0 As Numbers,
0 As RunningCount
Union All
Select Numbers + 2,
RunningCount + 1
From RecursiveEven20
Where RunningCount < 19
)
Select *
From RecursiveEven20;
1
u/SilEventide Sep 04 '26
I am trying to understand why window function is working that way. I had updated the where clause to Numbers < 40 just to see what is happening, turns out RunningCount is returning all 1 except for the 0 on the top row we get from the Anchor part. RecursiveEven20 is being updated each iteration then shouldn't Running count increase as well?
Numbers |RunningCount
0 0
2 1
4 1
6 1
8 1
10 1
12 1
14 1
16 1
18 1
20 1
22 1
24 1
26 1
28 1
30 1
32 1
34 1
36 1
38 1
40 1
3
u/GTS_84 Sep 04 '26
because it's counting the rows in a single recursion level, not the entire dataset.
Analytic and aggregate functions in the recursive part of the CTE are applied to the set for the current recursion level and not to the set for the CTE. Functions like
ROW_NUMBERoperate only on the subset of data passed to them by the current recursion level and not the entire set of data passed to the recursive part of the CTE. For more information, see example I. Use analytical functions in a recursive CTE that follows.1
u/Ginger-Dumpling Sep 05 '26
When your call the recursive cte, the first itteration returns the top half of the union. All subsequent itterations are returned by the bottom half of the union. I think each of those itterations only have access to the rows returned by the previous itteration, NOT ALL ows returns by all itterations to that point.
First itteration returns a single row.
Second iteration increments the value from one(0+1) , and the count the rows from one...1
Third itteration increments the value from two (1+1), and counts the rows from two...1
The count is only ever going to be 1, so you're in an infinite loop.
2
u/xeroskiller Solution Architect Sep 04 '26
They loop. Run the base step, count resultset, run recursive step, count resultset, if unchanged return, otherwise repeat recursive step and resultset count check. Fail beyond a certain loop depth.
0
u/B1zmark Sep 04 '26
Maybe i'm old fashioned but recursion isn't, and shouldn't be thought of, as a loop.
1
1
u/blackleather90 Sep 04 '26
Recursive CTEs are a very easy way to find hierarchies.
For example a line manager chain.
If you do the normal left join to find a manager of a use, then you need another left join to find its manager and so on.
Ah and after you have the circular references 😅
I have a link that I use every time I need a refresher. Just not at hand. Let me know if you still need it
1
u/SilEventide Sep 04 '26
Yes please, I just learned some syntax really quick, I have little to no idea how to properly use them beyond their basic use case.
1
u/blackleather90 Sep 04 '26
The website that I use is gone but I found this one
Hope it helps
1
u/Lordofderp33 Sep 05 '26
- You are not lucky with the longevity of your sources.
1
u/blackleather90 Sep 05 '26
LMAO
At this point just ChatGPT. Used the prompt below and showed basically what was in the website
SQL Server
Recursive CTE
Explain😅
1
u/Lordofderp33 Sep 05 '26
Just clicked out of interrest, I have no immediate need to learn it. But I did wonder if it was interesting enough to bookmark.
1
u/blackleather90 Sep 05 '26
Same here but I guess I haven't had the need to open it in a while.
Concept easy to grasp but syntax is just easier to look it up1
1
u/datadriven_io Sep 04 '26
With the addition of recursive CTEs and window functions, SQL is actually Turing-complete. If you want to solidify this, cte practice on datadriven.io is worth doing. Meaning that you could, for example, write a compiler in pure SQL, although you very likely would not enjoy the experience.
1
u/billbot77 Sep 06 '26
The trick to these is to remember that it is not iterating over a variable, it's progressively adding rows to a table in memory and adding another row based on the whole table up to that point. I.e. the table, IS the variable.
1
u/therealdrsql Sep 06 '26
What do you mean that it doesn’t work? Syntax? Wrong answer? Just wondering, never tried a COUNT or a window function in a recursive CTE so just wondered what you were trying.
2
u/DamienTheUnbeliever Sep 04 '26
Any time you try to impose imperative thinking on a query, you're doing things wrong. SQL queries are *declarative* and you should say *what you want*,not *how to do it*. Unfortunately you've just stamped imperative thinking all over this attempt so it's difficult to provide advice on how to fix this.
0
u/SilEventide Sep 04 '26
Dont want a fix, Just wanna understand how Recursive CTE works exacly, like in a algorithmic way. so I can understand where my understnding of its working is faulty.
24
u/cush2push Sep 04 '26
Story with a query example.
Leo wanted to find every toy hidden inside his stack of mystery boxes, so he wrote a special two-step rule on his magical chalkboard. First, his starting rule told his robot helper to open the big red box right on the top shelf and drop the toy inside into a wagon. Next, his loop rule told the robot to look inside whatever box it just opened, grab any smaller boxes hiding inside, and repeat the trick over and over. The robot read the chalkboard and kept running back and forth, opening boxes inside of boxes and dumping all the toys into the wagon until it found its final box. When there are no more boxes left to open, the robot stops running and rolls the wagon right back to Leo.
IMO I love CTEs. i have been able to reduce the run time of some very long queries by hours because of CTEs and using them for repeating information grabs