SQL GROUP BY
GROUP BY bundles rows that share the same value(s) so aggregate functions can summarise each bundle separately.
Anatomy of a grouped query
SQL
SELECT country, COUNT(*) AS customers FROM customers GROUP BY country ORDER BY customers DESC;
The "every column rule"
Every non-aggregated column in the SELECT list must appear in GROUP BY. This is enforced strictly in PostgreSQL and SQL Server, loosely in MySQL (with ONLY_FULL_GROUP_BY off — but that's a footgun that returns arbitrary values).
Grouping on multiple columns
SQL
SELECT country, city, COUNT(*) AS customers FROM customers GROUP BY country, city ORDER BY country, customers DESC;
Where each clause fires
| Step | Clause |
|---|---|
| 1 | FROM / JOIN |
| 2 | WHERE — filter rows |
| 3 | GROUP BY — bucket them |
| 4 | aggregates evaluated per bucket |
| 5 | HAVING — filter buckets |
| 6 | SELECT |
| 7 | ORDER BY |
| 8 | LIMIT |
Tip: If your group has unexpected duplicate rows, the issue is almost always a JOIN above the GROUP BY — not the grouping itself.
Example
Exercise
Bucket rows by country before counting.
SELECT country, COUNT(*) FROM customers
country;
Two words; clause that bundles rows.
Discussion
Loading…