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.
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.
| nametext | teamtext | pointsinteger | used by the function |
|---|---|---|---|
| Asha | Red | 31 | counted |
| Ben | Blue | 17 | counted |
| Chen | Red | NULL | counted |
| Dara | Green | 24 | counted |
| Eli | Blue | NULL | counted |
| Fay | Red | 24 | counted |
| Gus | Green | 40 | counted |
| Hana | Blue | 17 | counted |
| 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.
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.