iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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

StepClause
1FROM / JOIN
2WHERE — filter rows
3GROUP BY — bucket them
4aggregates evaluated per bucket
5HAVING — filter buckets
6SELECT
7ORDER BY
8LIMIT
Tip: If your group has unexpected duplicate rows, the issue is almost always a JOIN above the GROUP BY — not the grouping itself.

Example

Example
SELECT country, COUNT(*) AS customers
FROM customers
GROUP BY country;
Try it Yourself »

Exercise

Bucket rows by country before counting.

SELECT country, COUNT(*) FROM customers country;

Test yourself

Q1. Every non-aggregated SELECT column must appear in…
Q2. GROUP BY fires…
Q3. GROUP BY 1, 2 means…

Discussion

Loading…