Skip to main content

VillageSQL is a drop-in replacement for MySQL with extensions.

All examples on this page work on VillageSQL. Install Now →
Every query so far returned rows. An aggregate function reads many rows and returns 1 value: how many, the total, the average, the largest. It is the first thing you reach for when the question is about a set rather than a row. Open the client with mysql -u root -p sakila before you start.

How an aggregate function works

Replace 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

1 row, whatever the table holds. An aggregate always answers.

2) Several aggregates at once

Each one reads the same 1,000 rows. Name them with aliases, because the default heading is the whole expression.

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.
603 addresses, and 4 of them have no second line at all. The other 599 hold an empty string, which 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 to COUNT. 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 and COUNT(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 SUM and AVG when nothing qualifies.

See also