How do you create a recursive CTE to generate a series of numbers?
Posted by AliceWk
Last Updated: June 20, 2024
Creating a recursive Common Table Expression (CTE) to generate a series of numbers in SQL is a useful technique. Below is an example of how to do this. We'll demonstrate using a CTE in SQL Server, but similar logic applies to most SQL databases that support CTEs.
Example: Generating Numbers from 1 to 10
Here’s how you can create a recursive CTE to generate a series of numbers:
WITH NumberSeries AS (
    -- Anchor member: Start the series at 1
    SELECT 1 AS Number
    UNION ALL
    -- Recursive member: Increment the number by 1
    SELECT Number + 1 
    FROM NumberSeries
    WHERE Number < 10 -- Change 10 to your desired maximum number
)
SELECT Number
FROM NumberSeries;
Explanation:
1. Anchor Member: This part of the CTE initializes the number series. In this example, we start with the number 1. 2. Recursive Member: This part increments the value of Number by 1 for each recursion. It continues generating numbers as long as the condition WHERE Number < 10 is satisfied. 3. Final SELECT: After the CTE definition, we execute a SELECT statement to retrieve the numbers from the CTE.
Points to Note:
- Recursion Limit: Many databases have a limit on how many times a CTE can recursively call itself. For example, SQL Server has a default limit of 100 recursions, which you can change with the MAXRECURSION option, if necessary. - Performance: Be cautious when generating large series of numbers, as recursive CTEs can consume memory and processing resources. You can adjust the stopping condition in the WHERE clause to generate a different range of numbers or customize the starting point as needed.