SQL ยท Chapter 23 of 42
Aggregate Functions
Aggregates summarise a set of rows into a single value.
Main ones: `COUNT(*)`, `SUM(col)`, `AVG(col)`, `MIN(col)`, `MAX(col)`.
COUNT variants
`COUNT(*)` counts all rows. `COUNT(col)` skips NULLs. `COUNT(DISTINCT col)` counts unique non-NULL values.
SUM/AVG behaviour
SUM and AVG ignore NULL. AVG divides by the count of NON-NULL values.
Example 1 (sql)
SELECT COUNT(*), AVG(price), MAX(price)
FROM products;Output
count | avg | max
120 | 380 | 999Three aggregates in one row.
Example 2 (sql)
SELECT COUNT(DISTINCT country) AS countries FROM users;Output
countries
27How many unique countries our users come from.
Key points
- COUNT, SUM, AVG, MIN, MAX are core.
- NULLs are ignored by SUM/AVG/MIN/MAX.
- COUNT(*) counts rows including NULLs.
- Combine with GROUP BY for per-group aggregates.
๐ก Note: For medians and percentiles, PostgreSQL/Oracle have `PERCENTILE_CONT`. MySQL requires a workaround.
