VillageSQL is a drop-in replacement for MySQL with extensions.
All examples on this page work on VillageSQL. Install Now →
mysql -u root -p sakila before you start.
How an aggregate function works
AGGREGATE_FUNCTION with one of the functions below, COLUMN_NAME
with the column to read, and TABLE_NAME with the table.
With no
GROUP BY, the whole table is 1 group, so the result is always exactly
1 row. GROUP BY is how you get 1 row per category
instead.
Examples
1) Count the rows
2) Several aggregates at once
3) Total a money column
COUNT(*) and COUNT(column) are different questions
COUNT(*) counts rows. COUNT(column) counts the rows where that column holds
a value, so it skips NULL.
COUNT treats as a value like any other: it is looking for
NULL, not for blankness. The IS NULL lesson covers that
difference.
Every aggregate skips NULL
The rule is not special toCOUNT. No aggregate looks at a NULL, which means a
column with nothing in it produces nothing to average. Averaging an id is
meaningless arithmetic, and this query does it only because
original_language_id is the one column in Sakila that is NULL in every row.
AVG returned NULL rather than 0, because there was nothing to divide. That
matters most for AVG on a column that is only sometimes filled in: the mean
is over the rows that have a value, not over all the rows, and the 2 numbers
are not the same. SUM of nothing is NULL too, while COUNT of nothing is 0.
Summary
- Use an aggregate to reduce many rows to 1 value.
- Expect exactly 1 row back when there is no
GROUP BY. - Read
COUNT(*)as how many rows andCOUNT(column)as how many have a value. - Expect every aggregate to skip NULL, so an average is over the rows that have a value.
- Expect NULL rather than 0 from
SUMandAVGwhen nothing qualifies.
See also
- GROUP BY — 1 result row per category instead of 1 in total
- COUNT DISTINCT — counting different values rather than rows
- IS NULL — the values these functions skip
- MySQL GROUP BY performance — what aggregating costs at scale

