SQL GROUP BY and HAVING: Totals Per Group
The previous chapter turned the whole table into one summary row. GROUP BY produces one summary row per group instead: titles per genre, copies per author, revenue per month.
How grouping works
GROUP BY genre sorts the rows into buckets, one per distinct genre. Each aggregate in the SELECT list is then computed separately for each bucket. The plain columns you select should be the grouping columns; they are the same for every row in the bucket, so each group has one well-defined value for them.
In the first query of the example, the ten books form three groups. Fiction has four titles, and its most expensive one costs 17.25. ORDER BY titles DESC, genre sorts the summary rows, using the alias defined in SELECT.
HAVING filters groups
WHERE filters individual rows before grouping. HAVING filters whole groups after the aggregates are computed, so it can use them. The second query groups books by author, adds up their stock, and keeps only authors with more than 20 copies on the shelves.
Expected output
genre | titles | top_price Fiction | 4 | 17.25 Nonfiction | 3 | 24.5 Tech | 3 | 39.5 author_id | copies 5 | 34 4 | 23
The full order of evaluation
SQL clauses are written in one order and evaluated in another:
FROM(and joins) collects rows.WHEREfilters rows.GROUP BYforms groups.HAVINGfilters groups.SELECTcomputes the output columns.ORDER BYsorts, andLIMITtrims.
When a query surprises you, walk through it in that order.
Grouping by several columns
GROUP BY genre, year makes one group per distinct combination of genre and year. You can also group by an expression, for example GROUP BY substr(ordered_on, 1, 7) to group ISO dates by month.
Showing names instead of ids
The second query shows author_id, which is not very friendly. To show author names, join the authors table, which is the topic of the next chapter. Joins and GROUP BY are often used together.
Common mistakes
- Using
WHEREto filter on an aggregate; that isHAVING's job. - Selecting a column that is neither grouped nor aggregated. SQLite allows it but picks a value from an arbitrary row; other databases raise an error.
- Forgetting
ORDER BY; groups are not guaranteed to come out sorted.
Summary
GROUP BY colreturns one row per distinct value, with aggregates per group.WHEREfilters rows before grouping;HAVINGfilters groups after.- Evaluation order: FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT.
Quiz: GROUP BY and HAVING