5. Aggregates
COUNT, SUM, AVG and the art of GROUP BY.
The lesson
Aggregates
So far, every query answered with rows you could point at: these are the tracks, these are the customers. This chapter is different. Here you ask the table to summarize itself — not "show me the rows", but "tell me how many, how much, on average, the most, the least".
These summary functions are called aggregates, and the moment you master them you can answer real business questions: How many tracks do we sell? How much is the catalog worth? Which genre carries the store?
Counting: COUNT(*)
The simplest question of all — how many rows? — has a one-word function:
SELECT COUNT(*) AS total FROM tracks;
COUNT(*) counts every row in the table. The answer comes back as a single row with a single number: 49. Note what you don't get: no list of tracks, no details. The aggregate ate the table and spat out one number. That's the deal with aggregates — rows in, summary out.
COUNT(column) vs COUNT(*): the NULL trap
Now try counting the artists:
SELECT COUNT(*) AS total FROM artists; -- 12
SELECT COUNT(formed_year) AS with_year FROM artists; -- 10
Same table, different answers. Why? COUNT(*) counts rows — all twelve artists. COUNT(formed_year) counts values, and it skips NULL. Two bands (Nocturne Quartet, The Paper Cranes) never reported the year they formed, so their rows have NULL there, and they don't count.
This is the single most common aggregate mistake: COUNT(*) is "how many things are there?", while COUNT(column) is "how many things have a value here?". Use COUNT(column) whenever a missing value shouldn't count.
Adding and averaging: SUM and AVG
For money, SUM and AVG do exactly what their names promise:
SELECT SUM(unit_price) AS total_value, AVG(unit_price) AS avg_price
FROM tracks;
If a fan bought every track once, the store takes in 52.71 — and the average track costs about 1.08. Both aggregates ignore NULLs: SUM adds the values that exist, and AVG divides by the count of values, not the count of rows.
Averages are often long decimals — the one above is 1.0757.... That's normal; we'll learn to round in chapter 7.
MIN and MAX
Not everything is counting. The extremes are questions too:
SELECT MIN(duration_sec) AS shortest, MAX(duration_sec) AS longest
FROM tracks;
176 seconds for the shortest track, 402 for the longest. Same shape as before: one row of summary numbers.
You can also mix aggregates freely in one SELECT — COUNT, SUM, AVG, MIN, MAX are just functions, and a query can use several at once.
GROUP BY: one summary per group
Here's where it gets interesting. SELECT COUNT(*) FROM tracks gives one number for the whole table — but the store has eight genres, and the owner wants to know how many tracks each genre has. That's where GROUP BY comes in:
SELECT genre_id, COUNT(*) AS tracks
FROM tracks
GROUP BY genre_id;
Read it as: split the rows into groups by genre_id, then run the aggregate inside each group. The result has one row per genre:
| genre_id | tracks |
|---|---|
| 1 (Rock) | 11 |
| 2 (Jazz) | 6 |
| 3 (Soul) | 9 |
| 4 (Folk) | 8 |
| 5 (Electronic) | 6 |
| 6 (Classical) | 3 |
| 7 (Hip-Hop) | 3 |
| 8 (Bossa Nova) | 3 |
(We report the genre_id for now — turning ids into names requires a JOIN, which has its own chapter later.)
With GROUP BY, a rule appears: you can only SELECT the column you grouped by, plus aggregates. It would make no sense to ask for title when each group has three titles — which one should SQL pick? So: grouped columns and aggregates only.
HAVING: filtering groups
Once rows are grouped, WHERE can't touch them anymore — WHERE filters rows before grouping, and at that point COUNT(*) doesn't exist yet. Filtering groups is a different keyword, with a different position:
SELECT genre_id, COUNT(*) AS tracks
FROM tracks
GROUP BY genre_id
HAVING COUNT(*) > 5;
Five genres survive: Rock (11), Jazz (6), Soul (9), Folk (8) and Electronic (6). Notice the pattern: WHERE filters rows, HAVING filters groups. You can even use both in one query — WHERE trims rows first, then GROUP BY builds groups from what's left, then HAVING trims the groups.
The whole report together
The owner wants a per-album catalog report: track count, total duration, average price — but only for albums with three or more tracks, sorted by album. Everything you've learned stacks into one query:
SELECT album_id, COUNT(*) AS tracks,
SUM(duration_sec) AS total_seconds,
AVG(unit_price) AS avg_price
FROM tracks
GROUP BY album_id
HAVING COUNT(*) >= 3
ORDER BY album_id;
One query, four jobs: group, count, sum, average, filter, sort. Fifteen albums come back, each with its three summary numbers. That's the shape of most reporting SQL you'll write from now on.
What you just learned
COUNT(*)counts rows;COUNT(column)counts non-NULLvalues — they differ whenNULLs exist.SUM,AVG,MIN,MAXsummarize a column into one number, skippingNULLs.GROUP BYsplits rows into groups and runs the aggregates inside each — one result row per group.- With
GROUP BY, select only grouped columns and aggregates. WHEREfilters rows before grouping;HAVINGfilters the groups after.
Dialect note.
GROUP BYandHAVINGbehave identically in PostgreSQL, MySQL and SQL Server. One difference: SQLite is lenient and lets youSELECTcolumns that aren't grouped or aggregated (it just picks a value from one row). Other databases reject that as an error, and so should you — it's a trap, not a feature. In this course, always follow the rule: grouped columns and aggregates only.
Time to run some numbers. The exercises below assume you've read this far.