Learn SQL/Advanced/CTEs/SQL Basic CTE

SQL Basic CTE

Watch a CTE resolve into its own temporary result, then get queried like a real table.

What & Why

The Basic CTE pattern is used to define one Common Table Expression and read it from the final SELECT. This keeps the SQL aligned with one concrete business question and makes the result grain explicit before the query is reused.

See How It Works

BUSINESS QUESTION

Marketing wants qualified leads isolated before source-level counting.

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 one named table feed the final aggregationStep 1 of 2
qualified_leads → GROUP BY source → final result
idsource
301google_ads
303email
304linkedin

The qualified_leads CTE contains the ID and source for each lead with a qualification timestamp.

EXAMPLE QUERY
WITH qualified_leads AS (
  SELECT id, source
  FROM marketing.leads
  WHERE qualified_at IS NOT NULL
)
SELECT
  source,
  COUNT(*) AS qualified_leads
FROM qualified_leads
GROUP BY source
ORDER BY qualified_leads DESC, source;

This lesson's practice is part of Pro.

Advanced business practice

Sign up free to try it on a real business scenario