Aggregates and Grouping
Counting, summing, and the GROUP BY rule.
An aggregate turns many rows into one value.
The five aggregates
COUNT, SUM, MIN, MAX and AVG. Without GROUP BY the whole table is one group:
SELECT COUNT(*) AS n,
SUM(stock) AS total_stock,
MIN(price) AS cheapest,
MAX(price) AS dearest
FROM product;Five rows in, one row out. AVG needs rounding to be readable:
SELECT ROUND(AVG(price), 2) AS avg_price FROM product;COUNT(*) versus COUNT(column)
They are not the same, and the difference is NULL:
SELECT COUNT(*) AS count_star,
COUNT(value) AS count_value
FROM reading;CREATE TABLE reading (
id INTEGER,
label VARCHAR(20),
value INTEGER
);
INSERT INTO reading VALUES (1, 'first', 10), (2, 'second', NULL);COUNT(*) counts rows. COUNT(value) counts rows where value is not NULL.
GROUP BY
One output row per distinct value:
SELECT category, COUNT(*) AS n, SUM(stock) AS total_stock
FROM product
GROUP BY category
ORDER BY category;The aggregates now run per group rather than over the table.
The grouping rule
Every selected column must be grouped or aggregated. Break it and the engines disagree:
SELECT category, name, COUNT(*) FROM product GROUP BY category;Two rows share input but only one name can be shown, so the question has no answer.
Postgres and MySQL say so; SQLite picks one silently.
HAVING
HAVING filters groups, after aggregation:
SELECT category, COUNT(*) AS n
FROM product
GROUP BY category
HAVING COUNT(*) > 1
ORDER BY category;Only input has more than one product.
WHERE COUNT(*) > 1 is an error: WHERE runs before grouping, so no count exists yet.
WHERE versus HAVING
Same table, same grouping, different clause, different answer:
SELECT category, COUNT(*) AS n
FROM product
WHERE price > 50
GROUP BY category
ORDER BY category;WHERE dropped the two cheap rows before grouping, so input disappeared entirely rather
than showing a smaller count.
| Clause | Runs | Filters |
|---|---|---|
WHERE |
before grouping | rows |
HAVING |
after grouping | groups |
Grouping by an expression
Any expression works, and ORDER BY can use the alias:
SELECT category, ROUND(AVG(price), 2) AS avg_price
FROM product
GROUP BY category
ORDER BY avg_price DESC;Aggregates over no rows
An empty group is where COUNT and SUM part company:
SELECT COUNT(*) AS n, SUM(value) AS total
FROM reading
WHERE id = 99;COUNT gives 0, SUM gives NULL. A total that should read zero renders blank instead:
SELECT COALESCE(SUM(value), 0) AS total
FROM reading
WHERE id = 99;