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 | 999

Three aggregates in one row.

Example 2 (sql)
SELECT COUNT(DISTINCT country) AS countries FROM users;
Output
countries
27

How 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.

๐Ÿ“ Quick Quiz

1. Which counts ALL rows including NULLs?

2. AVG(col) ignores:

3. MAX returns: