What aggregate functions are there?
Aggregate functions reduce a set of rows to a single value: COUNT, SUM, AVG, MIN and MAX. COUNT gives the number of rows, SUM the total, AVG the mean, MIN and MAX the smallest and largest, including for dates and strings. All except COUNT(*) ignore NULL. Without GROUP BY the result is one row even for an empty set: COUNT returns 0, the others NULL.
SQL · Aggregates
A manager asks: how many transactions, what turnover and when was the last one. Is one query enough?
The screen says "Turnover for the period: 120" and a tester has to check that this number is right. Exporting thousands of rows and counting by hand is slow and unreliable: the database can count by itself. This lesson is about aggregate functions: what exactly they do with rows, where in the query they run and where their behaviour surprises.
How it works and why. An aggregate function reads a set of rows and returns one value for the whole set. Without GROUP BY the set is all rows that passed WHERE, so the result is exactly one row (unless the query has HAVING). Even when there are no rows, the database does not return "nothing": COUNT gives 0 and the other functions give NULL.
Many rows collapse into one
| Function | What it computes | NULL on input | Empty set |
|---|---|---|---|
COUNT(*) | the number of rows | the row is counted | 0 |
COUNT(col) | rows where col is not NULL | ignores | 0 |
SUM(col) | the sum | ignores | NULL |
AVG(col) | the average | ignores | NULL |
MIN, MAX | the smallest and the largest | ignores | NULL |
Result types matter too. MIN and MAX work not only with numbers but with anything that can be ordered: dates and strings (strings are compared by the collation rules, so "a" and "B" may order differently than you expect). In PostgreSQL SUM of integer returns bigint and AVG of integers returns numeric, so the average of 30 and 31 is 30.5, not 30.
Example: from an export to one query. The "turnover for the period" report is checked like this:
SELECT COUNT(*) AS total,
SUM(amount) AS volume,
AVG(amount) AS avg_amount,
MAX(amount) AS max_amount
FROM transactions
WHERE status = 'completed';
-- one row: 3, 120, 40.0000…, 50
The WHERE filter runs first, so the failed transaction (20) never reaches the aggregate. That is why the "turnover" here is 120, not 140.
What the aggregate sees after WHERE
| id | status | amount |
|---|---|---|
| 1 | completed | 50 |
| 2 | completed | 30 |
| 3 | failed | 20 filtered out |
| 4 | completed | 40 |
| total | volume | max_amount |
|---|---|---|
| 3 | 120 | 50 |
Limits and alternatives. An aggregate without GROUP BY cannot be mixed with a plain column in SELECT: the database does not know which of many status values to show. Nesting aggregates (SUM(COUNT(*))) without a subquery is forbidden in PostgreSQL too. And if an empty set must give a number rather than NULL, the result is wrapped in COALESCE (a separate lesson in this chapter). Besides the five classic functions, dialects have useful extensions:
-- PostgreSQL: all statuses of a user in one row
SELECT account_id,
STRING_AGG(DISTINCT status, ', ' ORDER BY status) AS statuses
FROM transactions
GROUP BY account_id;
-- MySQL: GROUP_CONCAT(DISTINCT status)
If you need to keep all rows and add a total to each one (for example a share of the grand total), window functions fit: they compute over the same set but do not collapse it into one row.
Common mistakes.
-- error: an aggregate and a plain column without GROUP BY
SELECT status, COUNT(*) FROM transactions;
-- an empty set: still exactly one row
SELECT COUNT(*), SUM(amount), MAX(amount)
FROM transactions
WHERE id = -1;
-- 0 | NULL | NULL
- Adding a plain column to an aggregate without
GROUP BY: an error, and in some MySQL settings and in SQLite the query runs and shows a random value. - Expecting 0 from
SUMon an empty set: it is NULL, and the client shows an empty field. - Forgetting that
WHEREdrops rows before the aggregate: "turnover" without a status filter includes failed transactions too. - Computing
AVGof integers by hand in code with integer division: the fraction is lost. - Finding the largest row with
MAXand taking other fields at once:MAXreturns only the value, not the whole row.
Check yourself
The query SELECT COUNT(*), SUM(amount) FROM transactions WHERE id = -1 runs without errors. How many rows does it return and what is in them?
Answer
Exactly one row: COUNT gives 0 and SUM gives NULL. An aggregate without GROUP BY always returns one row, even when no row passed WHERE. A test that expects an "empty result" will be wrong here.
Why does SELECT status, COUNT(*) FROM transactions fail?
Answer
An aggregate collapses the set into one value, while status has many different values and the database does not know which to show. Either add GROUP BY status or choose an aggregate for status too (for example MIN(status)).
The table has amounts 100, NULL, 200. Why is AVG(amount) 150 and not 100?
Answer
AVG ignores NULL both in the sum and in the count: (100 + 200) / 2. If NULL were treated as zero it would be (100 + 0 + 200) / 3 = 100. Which variant is right is decided by the business rule.