1.Generate the numbers 1 to 5
AdvancedWithout using any table, return the numbers 1 to 5 in a column called n, using a recursive CTE.
Show hint
The anchor part selects 1. The recursive part selects n + 1 from the CTE itself, while n < 5.
Show solution
WITH RECURSIVE numbers(n) AS (
SELECT 1
UNION ALL
SELECT n + 1 FROM numbers WHERE n < 5
)
SELECT n FROM numbers;n
-
1
2
3
4
5The WHERE n < 5 condition is what stops the recursion. Without it the query would run forever (or until the database's recursion limit). SQL Server and Oracle write just WITH, without RECURSIVE.