Learn SQL/Advanced/CTEs/SQL CTE vs Subquery

SQL CTE vs Subquery

Often the same query plan under the hood — the difference is almost entirely for the human reading it.

What & Why

A CTE and an equivalent subquery frequently produce the identical result and the identical execution plan. The real difference: a CTE is named and can be reused more than once in the same query; a subquery is inline and read where it sits.

See How It Works

BUSINESS QUESTION

Compare named and inline channel-spend summaries that return the same rows.

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
Compare named and inline versions of the same result tableStep 1 of 2
WITH channel_spend AS (...) SELECT ... FROM channel_spend
channeltotal_spendCTE result
google_ads115,000.00KEEP
linkedin50,000.00KEEP
email45,000.00SKIP

The named channel_spend CTE exposes the three-row intermediate table before filtering.

EXAMPLE QUERY
-- Named intermediate result
WITH channel_spend AS (
  SELECT channel, SUM(spend) AS total_spend
  FROM marketing.campaigns
  GROUP BY channel
)
SELECT channel, total_spend
FROM channel_spend
WHERE total_spend >= 50000
ORDER BY total_spend DESC;

-- Equivalent inline intermediate result
SELECT channel, total_spend
FROM (
  SELECT channel, SUM(spend) AS total_spend
  FROM marketing.campaigns
  GROUP BY channel
) AS channel_spend
WHERE total_spend >= 50000
ORDER BY total_spend DESC;

This lesson's practice is part of Pro.

Advanced business practice

Sign up free to try it on a real business scenario