Learning navigation

Code with Animation

Aggregate Functions

Turn many rows into one answer with count, sum, avg, min and max, and learn exactly how each one treats NULL and empty results.

SQL6 min readConcept 19 of 44

Many rows in, one value out

An aggregate function reads a set of rows and returns a single value. The five you will use most are count, sum, avg (average), min and max.

A query that only has aggregates in its SELECT list returns exactly one row: SELECT count(*), max(points) FROM players;.

Questions about the whole table

"How many players are there?", "What is the best score?" and "What is the average?" are questions about a whole set of rows. Asking the database is faster and safer than downloading every row and adding them up in your own code.

NULL changes the numbers

SELECT count(*), count(points), sum(points), avg(points)
FROM players;

The players table has 8 rows, but Chen and Eli have NULL points. The result is 8, 6, 153 and 25.5.

count(*) counts rows, whatever is inside them. count(points) counts only the rows where points is not NULL. sum, avg, min and max also skip NULL. So avg is 153 divided by 6 values, not by 8 rows.

count(DISTINCT team) counts each different team once, so it gives 3. Adding FILTER (WHERE ...) after an aggregate limits only that one aggregate, for example count(*) FILTER (WHERE points >= 24).

See which rows each function uses

Pick a function and read the last column: it shows which rows are used and which are skipped. Then switch to the WHERE points > 100 rows and see what each function returns for nothing.

SELECT count(*)
FROM players;
players (8 rows)
nametextteamtextpointsintegerused by the function
AshaRed31counted
BenBlue17counted
ChenRedNULLcounted
DaraGreen24counted
EliBlueNULLcounted
FayRed24counted
GusGreen40counted
HanaBlue17counted
Result (1 row)
countbigint
8

count(*) counts rows, whatever is in them. All 8 players are counted, even the two with NULL points.

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1`players` has 8 rows and 2 of them have NULL `points`. What does `count(points)` return?
  2. 2A column holds the values 10, 20 and NULL. What does `avg(column)` return?
  3. 3A query selects `count(*)` and `sum(points)` but no row passes the WHERE test. What does it return?

Remember this

  • An aggregate function turns a set of rows into one value: count, sum, avg, min, max.
  • count(*) counts rows. count(column), sum, avg, min and max skip NULL values.
  • On no rows, count gives 0 and the others give NULL, not 0.
  • An aggregate cannot be used in WHERE, because WHERE runs before the aggregate is computed.

Done with this concept?

Mark it complete to track your progress. No login needed.