Learn SQL/Advanced/CTEs/SQL Recursive CTE

SQL Recursive CTE

A CTE that references itself — built for data a normal query can't walk on its own.

What & Why

A recursive CTE runs in two parts: an anchor query that picks a starting point, and a recursive query that repeats, each time building on the previous round's result — until a round produces nothing new.

It's the tool for hierarchical data: an org chart, a category tree, a comment thread's replies — anything a single-pass query can't walk on its own because you don't know in advance how many levels deep it goes.

See How It Works

BUSINESS QUESTION

Generate every calendar day between the earliest and latest campaign start dates.

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
Watch a recursive CTE append one calendar row per iterationStep 1 of 3
anchor 2024-01-15 · add 1 day until 2024-04-01
iterationdaylast_daystate
anchor2024-01-152024-04-01CURRENT

The anchor reads the earliest and latest marketing.campaigns start dates.

EXAMPLE QUERY
WITH RECURSIVE bounds AS (
  SELECT MIN(start_date) AS first_day, MAX(start_date) AS last_day
  FROM marketing.campaigns
),
date_spine(day, last_day) AS (
  SELECT first_day, last_day FROM bounds
  UNION ALL
  SELECT day + 1, last_day
  FROM date_spine
  WHERE day < last_day
)
SELECT day
FROM date_spine
ORDER BY day;

This lesson's practice is part of Pro.

Advanced business practice

Sign up free to try it on a real business scenario