Aggregate Functions

Basic SQL
≈ 1 min read

An aggregate function takes a set of rows and returns a summary

A regular column in SELECT gives a value for each row. An aggregate function works with a whole set of rows and calculates one result from that set.

SELECT COUNT(*)
FROM orders;

If the orders table contains 250 rows, the query result contains one row with the value 250. The original rows remain in the table — aggregation changes only the shape of the query result.

Common aggregate functions

  • COUNT — the number of rows or known values;
  • SUM — the sum of values;
  • AVG — the average value;
  • MIN — the minimum value;
  • MAX — the maximum value.

Before aggregation, the result can be filtered with the familiar WHERE. The function then works only with rows that passed the filter.

SELECT COUNT(*)
FROM orders
WHERE status = 'PAID';
An aggregate function answers a question about a set of rows. If the question is “how many,” “what total,” “what average,” “what minimum,” or “what maximum,” the query probably needs aggregation.