SQL WITH RECURSIVE
The exact syntax behind the recursive CTE you just watched run round by round.
What & Why
WITH RECURSIVE is the keyword pair that makes a CTE allowed to reference itself. Structurally, it's an anchor query, a UNION ALL, and a recursive query that joins back to the CTE's own name.
See How It Works
BUSINESS QUESTION
Marketing wants the first five days from a date spine spanning the earliest through latest campaign start date.
| id | name | channel | spend | start_date | end_date | status | target_segment |
|---|---|---|---|---|---|---|---|
| 1 | Spring Launch | google_ads | 55000.00 | 2024-01-15 | 2024-03-31 | active | smb |
| 2 | Retention Webinar | 45000.00 | 2024-02-10 | 2024-04-15 | active | enterprise | |
| 3 | Finance Retargeting | 50000.00 | 2024-03-12 | 2024-05-31 | active | enterprise | |
| 4 | Enterprise Search | google_ads | 60000.00 | 2024-04-01 | 2024-06-30 | active | enterprise |
EXAMPLE QUERY
WITH RECURSIVE date_spine(day) AS (
SELECT MIN(start_date) FROM marketing.campaigns
UNION ALL
SELECT day + 1
FROM date_spine
WHERE day < (SELECT MAX(start_date) FROM marketing.campaigns)
)
SELECT day
FROM date_spine
ORDER BY day
LIMIT 5;RESULT — first five campaign-spine dates
| day |
|---|
| 2024-01-15 |
| 2024-01-16 |
| 2024-01-17 |
| 2024-01-18 |
| 2024-01-19 |
The recursive CTE generates all 78 dates through 2024-04-01; the final LIMIT returns these first five rows.
This lesson's practice is part of Pro.
Sign up free to try it on a real business scenario