Learn SQL/Advanced/CTEs/SQL WITH RECURSIVE

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.

idnamechannelspendstart_dateend_datestatustarget_segment
1Spring Launchgoogle_ads55000.002024-01-152024-03-31activesmb
2Retention Webinaremail45000.002024-02-102024-04-15activeenterprise
3Finance Retargetinglinkedin50000.002024-03-122024-05-31activeenterprise
4Enterprise Searchgoogle_ads60000.002024-04-012024-06-30activeenterprise
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.

Advanced business practice

Sign up free to try it on a real business scenario