📖 Scenario: You are working with a database that needs a list of numbers from 1 to 10 for a report. Instead of manually typing each number, you will use a recursive query to generate this list automatically.
🎯 Goal: Create a recursive Common Table Expression (CTE) in SQL that generates a series of numbers from 1 to 10.
📋 What You'll Learn
Create a recursive CTE named number_series starting with the number 1.
Use recursion to add the next number by incrementing the previous number by 1.
Stop the recursion when the number reaches 10.
Select all numbers from the number_series CTE.
💡 Why This Matters
🌍 Real World
Generating sequences of numbers or dates is common in reports, data analysis, and filling missing data in databases.
💼 Career
Understanding recursive CTEs helps database developers and analysts automate repetitive data generation tasks efficiently.
Progress0 / 4 steps
1
Create the base case of the recursive CTE
Write the first part of the recursive CTE named number_series that starts with the number 1. Use WITH RECURSIVE number_series AS (SELECT 1 AS num to begin.
SQL
Hint
Start the recursive CTE by selecting the number 1 as the base case.
2
Add the recursive part to increment the number
Add the recursive part of the CTE using UNION ALL and select num + 1 from number_series. Use WHERE num < 10 to stop at 10.
SQL
Hint
Use UNION ALL to combine the base case with the recursive step that adds 1 to the previous number.
3
Close the recursive CTE and select the series
Close the recursive CTE with a closing parenthesis ) and write a SELECT num FROM number_series statement to get the full series.
SQL
Hint
Close the CTE and select all numbers generated by it.
4
Complete the query with ordering
Add ORDER BY num ASC at the end of the query to display the numbers in ascending order.
SQL
Hint
Ordering the results makes the output easier to read.
Practice
(1/5)
1. What is the main purpose of using a Recursive CTE in SQL for series generation?
easy
A. To generate a sequence of numbers or dates step-by-step within a query
B. To join two tables based on a common column
C. To delete duplicate rows from a table
D. To create indexes for faster searching
Solution
Step 1: Understand Recursive CTE usage
Recursive CTEs are used to repeatedly execute a query to build results step-by-step.
Step 2: Identify series generation purpose
They are commonly used to generate sequences like numbers or dates without needing extra tables.
Final Answer:
To generate a sequence of numbers or dates step-by-step within a query -> Option A
2. Which of the following is the correct syntax to start a recursive CTE named numbers generating numbers from 1?
easy
A. WITH RECURSIVE numbers AS SELECT 1 AS num UNION ALL SELECT num + 1 FROM numbers WHERE num < 5
B. WITH RECURSIVE numbers AS (SELECT 1 AS num UNION ALL SELECT num + 1 FROM numbers WHERE num < 5)
C. WITH numbers RECURSIVE AS (SELECT 1 AS num UNION ALL SELECT num + 1 FROM numbers WHERE num < 5)
D. WITH RECURSIVE numbers (num) AS (SELECT 1 AS n UNION ALL SELECT num + 1 FROM numbers WHERE num < 5)
Solution
Step 1: Check correct WITH RECURSIVE syntax
The correct syntax starts with WITH RECURSIVE cte_name AS ( ... ).
Step 2: Validate the recursive query structure
WITH RECURSIVE numbers AS (SELECT 1 AS num UNION ALL SELECT num + 1 FROM numbers WHERE num < 5) correctly uses SELECT 1 AS num as anchor and recursive part with UNION ALL and stopping condition.
Final Answer:
WITH RECURSIVE numbers AS (SELECT 1 AS num UNION ALL SELECT num + 1 FROM numbers WHERE num < 5) -> Option B
Quick Check:
Correct recursive CTE syntax = WITH RECURSIVE numbers AS (SELECT 1 AS num UNION ALL SELECT num + 1 FROM numbers WHERE num < 5) [OK]
Hint: Start recursive CTE with WITH RECURSIVE cte AS (...) [OK]
Common Mistakes:
Placing RECURSIVE after CTE name
Missing parentheses around CTE query
Omitting AS keyword
3. Given the query:
WITH RECURSIVE seq AS (
SELECT 1 AS n
UNION ALL
SELECT n + 2 FROM seq WHERE n < 7
)
SELECT * FROM seq;
What will be the output rows?
medium
A. [1, 3, 5]
B. [1, 2, 3, 4, 5, 6, 7]
C. [1, 3, 5, 7]
D. [2, 4, 6, 8]
Solution
Step 1: Analyze anchor and recursive step
Anchor row is 1. Recursive step adds 2 each time: 1, 3, 5, 7.
Step 2: Check stopping condition
Recursion stops when n < 7 is false. Since 7 is included, sequence ends at 7.
Final Answer:
[1, 3, 5, 7] -> Option C
Quick Check:
Start=1, step=+2, stop at 7 = [1,3,5,7] [OK]
Hint: Add step value repeatedly until condition fails [OK]
Common Mistakes:
Assuming step is 1 instead of 2
Stopping before reaching 7
Including numbers beyond 7
4. Identify the error in this recursive CTE:
WITH RECURSIVE count_up AS (
SELECT 1 AS num
UNION ALL
SELECT num + 1 FROM count_up
)
SELECT * FROM count_up WHERE num <= 3;
medium
A. Using UNION instead of UNION ALL
B. Incorrect anchor query syntax
C. Wrong column alias in SELECT statements
D. Missing stopping condition inside the recursive part causing infinite recursion
Solution
Step 1: Check recursive part for stopping condition
The recursive SELECT lacks a WHERE clause to stop recursion, causing infinite loop.
Step 2: Understand WHERE clause placement
The WHERE clause outside the CTE filters final results but does not stop recursion inside CTE.
Final Answer:
Missing stopping condition inside the recursive part causing infinite recursion -> Option D
Quick Check:
Stopping condition must be inside recursive CTE [OK]
Hint: Put stopping condition inside recursive SELECT, not outside [OK]
Common Mistakes:
Placing stopping condition only in final SELECT
Confusing UNION and UNION ALL effects
Incorrect alias usage
5. You want to generate a list of dates from '2024-01-01' to '2024-01-05' using a recursive CTE. Which query correctly produces this date series?
hard
A. WITH RECURSIVE dates AS (SELECT DATE('2024-01-01') AS dt UNION ALL SELECT dt + INTERVAL '1 day' FROM dates WHERE dt < '2024-01-05') SELECT * FROM dates;
B. WITH RECURSIVE dates AS (SELECT '2024-01-01' AS dt UNION ALL SELECT dt + INTERVAL 1 DAY FROM dates WHERE dt <= '2024-01-05') SELECT * FROM dates;
C. WITH RECURSIVE dates AS (SELECT '2024-01-01' AS dt UNION ALL SELECT dt + 1 FROM dates WHERE dt < '2024-01-05') SELECT * FROM dates;
D. WITH RECURSIVE dates AS (SELECT DATE('2024-01-01') AS dt UNION ALL SELECT DATE(dt, '+1 day') FROM dates WHERE dt < '2024-01-05') SELECT * FROM dates;
Solution
Step 1: Understand date addition syntax
WITH RECURSIVE dates AS (SELECT DATE('2024-01-01') AS dt UNION ALL SELECT dt + INTERVAL '1 day' FROM dates WHERE dt < '2024-01-05') SELECT * FROM dates; uses dt + INTERVAL '1 day' which is standard SQL for adding one day to a date.
Step 2: Check stopping condition and anchor
Anchor selects the start date as DATE type. Recursive part adds one day while date is less than '2024-01-05'.
Step 3: Compare other options
WITH RECURSIVE dates AS (SELECT DATE('2024-01-01') AS dt UNION ALL SELECT DATE(dt, '+1 day') FROM dates WHERE dt < '2024-01-05') SELECT * FROM dates; uses SQLite style DATE(dt, '+1 day'), which is not standard SQL. WITH RECURSIVE dates AS (SELECT '2024-01-01' AS dt UNION ALL SELECT dt + INTERVAL 1 DAY FROM dates WHERE dt <= '2024-01-05') SELECT * FROM dates; uses incorrect WHERE condition allowing extra date. WITH RECURSIVE dates AS (SELECT '2024-01-01' AS dt UNION ALL SELECT dt + 1 FROM dates WHERE dt < '2024-01-05') SELECT * FROM dates; adds integer to date incorrectly.
Final Answer:
WITH RECURSIVE dates AS (SELECT DATE('2024-01-01') AS dt UNION ALL SELECT dt + INTERVAL '1 day' FROM dates WHERE dt < '2024-01-05') SELECT * FROM dates; -> Option A
Quick Check:
Date + INTERVAL '1 day' is standard SQL date addition [OK]
Hint: Use INTERVAL '1 day' to add days in standard SQL [OK]
Common Mistakes:
Using database-specific date functions in standard SQL
Incorrect stopping condition allowing extra dates
Adding integer directly to date without INTERVAL
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.