Aggregates and GROUP BY
Aggregate functions turn many rows into one summary value. They answer business questions like "How many orders did we get?" or "What's our average price?"
| Function | Returns |
|---|---|
COUNT(*) |
number of rows |
COUNT(col) |
number of non-NULL values |
SUM(col) |
total |
AVG(col) |
average |
MIN(col) / MAX(col) |
smallest / largest |
GROUP BY: one summary per group
GROUP BY splits rows into groups and runs the aggregate once per group.
The golden rule: every column in
SELECTmust either be in theGROUP BYor be inside an aggregate function. Otherwise, which row's value should the database show? (SQLite and MySQL may allow it silently and give you a random row. PostgreSQL refuses.)
HAVING: filtering groups
WHERE filters rows before grouping. HAVING filters groups after aggregating.
Logical order of execution
SQL is written in one order but executed in another. This explains why you can't use a SELECT alias inside WHERE:
FROM: pick the table(s)WHERE: filter rowsGROUP BY: form groupsHAVING: filter groupsSELECT: compute the output columnsORDER BY: sortLIMIT: cut
Grouping by dates
(strftime is SQLite. PostgreSQL uses date_trunc('month', order_date), MySQL uses DATE_FORMAT.)
Practice
- Find the total units ordered per product_id, highest first.
- Find the categories whose average price is above 20.
1.What's the difference between WHERE and HAVING?
2.What does COUNT(email) count?