Learn SQL/Advanced/CTEs/SQL Multiple CTEs

SQL Multiple CTEs

One WITH, separated by commas — each CTE resolves independently of the others.

What & Why

You can define more than one CTE in a single WITH — separate them with commas. Each one is independent of the others (unless you deliberately chain them, covered next) and can be referenced separately in the final query.

See How It Works

BUSINESS QUESTION

Prepare active campaigns and lead totals independently, then join the two named tables.

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
idcampaign_idemailcreated_atqualified_atconverted_atlead_scoresourcecountry
3011ana@example.com2024-01-21 09:10:00+002024-01-22 11:00:00+002024-02-02 10:00:00+0086google_adsUS
3021ben@example.com2024-01-24 12:40:00+00NULLNULL52google_adsCA
3032chloe@example.com2024-02-16 08:30:00+002024-02-18 14:20:00+00NULL74emailGB
3043dev@example.com2024-03-20 17:15:00+002024-03-21 09:00:00+002024-04-04 16:00:00+0091linkedinUS
Watch two independent CTE tables join into one resultStep 1 of 3
active_campaigns AS (SELECT ... FROM marketing.campaigns WHERE status = 'active')
campaign_idnamechannel
1Spring Launchgoogle_ads
2Retention Webinaremail
3Finance Retargetinglinkedin
4Enterprise Searchgoogle_ads

The first independent CTE returns the four active campaign rows.

EXAMPLE QUERY
WITH active_campaigns AS (
  SELECT id AS campaign_id, name, channel
  FROM marketing.campaigns
  WHERE status = 'active'
),
lead_totals AS (
  SELECT campaign_id, COUNT(*) AS leads
  FROM marketing.leads
  WHERE campaign_id IS NOT NULL
  GROUP BY campaign_id
)
SELECT
  a.campaign_id,
  a.name,
  a.channel,
  COALESCE(l.leads, 0) AS leads
FROM active_campaigns a
LEFT JOIN lead_totals l ON l.campaign_id = a.campaign_id
ORDER BY a.campaign_id;

This lesson's practice is part of Pro.

Advanced business practice

Sign up free to try it on a real business scenario