SQL COUNT OVER

Headcount per group, attached to every row in that group.

What & Why

COUNT(*) OVER (PARTITION BY ...) counts how many rows are in each partition — useful for showing "how many other rows am I grouped with" directly alongside the data.

See How It Works

BUSINESS QUESTION

Marketing wants each lead beside the number of leads from its source.

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
EXAMPLE QUERY
SELECT
  id AS lead_id,
  source,
  COUNT(*) OVER (PARTITION BY source) AS source_leads
FROM marketing.leads
ORDER BY source, lead_id;
RESULT — source count beside every lead
lead_idsourcesource_leads
303email1
301google_ads2
302google_ads2
304linkedin1

COUNT OVER preserves every lead while adding its source-group size.

This lesson's practice is part of Pro.

Advanced business practice

Sign up free to try it on a real business scenario