Aggregation with GROUP BY and HAVING
Summarising data with COUNT, SUM, AVG and friends, grouping by dimensions, and filtering aggregated results.
Beginner · about 5 hours · difficulty 2/5
Learn first: SQL Basics: SELECT, WHERE, ORDER BY
Aggregation is where SQL starts answering business questions: revenue per month, users per country, average basket size per channel.
The pattern
SELECT country,
COUNT(*) AS orders,
COUNT(DISTINCT customer_id) AS customers,
SUM(amount) AS revenue,
SUM(amount) / COUNT(DISTINCT customer_id) AS revenue_per_customer
FROM orders
WHERE status = 'completed'
GROUP BY country
HAVING COUNT(*) >= 100
ORDER BY revenue DESC;
- Every non-aggregated column in SELECT must appear in GROUP BY.
- WHERE filters rows before grouping; HAVING filters groups after.
COUNT(*)counts rows;COUNT(col)skips NULLs;COUNT(DISTINCT col)counts unique values.AVGignores NULLs, which may or may not be what you want.
Conditional aggregation
One of the most useful tricks: pivot inside SQL.
SUM(CASE WHEN channel = 'mobile' THEN amount ELSE 0 END) AS mobile_revenue
Some dialects offer COUNT(*) FILTER (WHERE ...) (PostgreSQL) or COUNTIF (BigQuery).
Sanity checks
Compare your grouped totals to an ungrouped total. If the sum of segments does not match, you have duplicates, NULL groups, or filters in the wrong place.
Pitfall: integer division (5 / 2 = 2 in some databases). Cast to decimal before dividing ratios. Move on when you can produce a multi-metric summary table with conditional aggregation in one query.
Key concepts
- COUNT, SUM, AVG, MIN, MAX
- GROUP BY multiple columns
- HAVING vs WHERE
- COUNT DISTINCT
- Conditional aggregation with CASE
- Integer division and casting
- ROLLUP and GROUPING SETS
Mini project
With the Chinook database, produce a single table of revenue, invoice count, distinct customers and average invoice value per country per year, only for countries with at least 10 invoices.
Check yourself
What is the difference between COUNT(*), COUNT(email) and COUNT(DISTINCT email)?
Free resources
- Mode SQL Tutorial (Mode)
- SQLBolt (SQLBolt)
- PostgreSQL tutorial (PostgreSQL)