QA Interview Hub · Knowledge base · Quizzes · Українська

SQL › Aggregation

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

amount: 4 rows1 row50302040COUNT(*) = 4SUM = 140AVG = 35MAX = 50
Figure 1. An aggregate leaves no separate rows: the output is one value per function.
FunctionWhat it computesNULL on inputEmpty set
COUNT(*)the number of rowsthe row is counted0
COUNT(col)rows where col is not NULLignores0
SUM(col)the sumignoresNULL
AVG(col)the averageignoresNULL
MIN, MAXthe smallest and the largestignoresNULL

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

transactions
idstatusamount
1completed50
2completed30
3failed20 filtered out
4completed40
result
totalvolumemax_amount
312050
Figure 2. WHERE removes row 3 before the computation: the aggregate works with three rows only.

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 SUM on an empty set: it is NULL, and the client shows an empty field.
  • Forgetting that WHERE drops rows before the aggregate: "turnover" without a status filter includes failed transactions too.
  • Computing AVG of integers by hand in code with integer division: the fraction is lost.
  • Finding the largest row with MAX and taking other fields at once: MAX returns 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.

In an interview. Junior: Aggregate functions collapse many rows into one value: COUNT counts, SUM sums, AVG averages, MIN and MAX give the extremes, and not only for numbers but for dates too. For example MAX of the creation date shows when the last transaction happened. Middle/Senior: An aggregate works after WHERE, and without GROUP BY it always returns one row, even on an empty set: COUNT gives 0, the rest NULL. All but COUNT(*) ignore NULL, so I check the result type and what the client does with NULL. To verify a report I count in SQL rather than by hand.

More articles in this chapter