It's Autumn! Prices fall like leaves! - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
The very basics
6. Recursion explained: syntax 2
Infinite looping
Processing graphs with recursive CTEs
Summary

Instruction

Now, let's discuss the remaining parts of our example query. We'll paste it here again for your convenience:

recursion

First of all, note that we used UNION ALL to join the anchor member (SELECT 1) with all further recursive steps (SELECT previous_value + 1). Instead of UNION ALL, we could also use UNION, which will remove duplicate values from the recursion. There are no duplicate values in this case, so in this instance there is no difference between UNION and UNION ALL.

Once the recursive CTE is completed and our temporary table is created, we need to query this table to see any results. That's why we put

SELECT * FROM counter

outside the CTE. This part of the query is called the invocation.

The animation below shows how our final recursive table is constructed.

Recursion query
Restart animation

Technically speaking, recursive CTEs do not use recursion; they use iterations. Still, as the SQL keyword for this kind of queries is RECURSIVE, it is common to call them recursion queries. Treat it as some sort of naming convention rather than a technically accurate description.

Exercise

Modify the example query so that it shows numbers from 20 to 5 (inclusive, in descending order).

Stuck? Here's a hint!

Your anchor member will now be 20, because that's the starting point. Instead of adding one each time, subtract one. Continue the operation as long as the previous value is greater than 5.