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.
| id | campaign_id | created_at | qualified_at | converted_at | lead_score | source | country | |
|---|---|---|---|---|---|---|---|---|
| 301 | 1 | ana@example.com | 2024-01-21 09:10:00+00 | 2024-01-22 11:00:00+00 | 2024-02-02 10:00:00+00 | 86 | google_ads | US |
| 302 | 1 | ben@example.com | 2024-01-24 12:40:00+00 | NULL | NULL | 52 | google_ads | CA |
| 303 | 2 | chloe@example.com | 2024-02-16 08:30:00+00 | 2024-02-18 14:20:00+00 | NULL | 74 | GB | |
| 304 | 3 | dev@example.com | 2024-03-20 17:15:00+00 | 2024-03-21 09:00:00+00 | 2024-04-04 16:00:00+00 | 91 | US |
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_id | source | source_leads |
|---|---|---|
| 303 | 1 | |
| 301 | google_ads | 2 |
| 302 | google_ads | 2 |
| 304 | 1 |
COUNT OVER preserves every lead while adding its source-group size.
This lesson's practice is part of Pro.
Sign up free to try it on a real business scenario