SQL Aggregate Functions
Aggregate functions turn many rows into one value: how many, what total, what average. On their own they summarise the whole table; with GROUP BY they summarise each group.
Updated December 1, 2026
Syntax
SELECT COUNT(*), SUM(column), AVG(column), MIN(column), MAX(column)
FROM table_name;
Summarise a whole table
One query, five answers about the product catalogue.
SELECT COUNT(*) AS products,
SUM(stock) AS units_in_stock,
ROUND(AVG(price), 2) AS avg_price,
MIN(price) AS cheapest,
MAX(price) AS priciest
FROM products;
| products | units_in_stock | avg_price | cheapest | priciest |
|---|---|---|---|---|
| 10 | 1293 | 67.45 | 4 | 249 |
Combine with WHERE
WHERE filters rows before they’re aggregated. Total drinks sold in the first three days of July:
SELECT SUM(quantity) AS drinks_sold
FROM orders
WHERE ordered_on <= '2024-07-03';
| drinks_sold |
|---|
| 9 |
COUNT(*) vs COUNT(column) vs COUNT(DISTINCT)
COUNT(*) counts rows, COUNT(column) counts non-null values, and COUNT(DISTINCT column) counts different values.
SELECT COUNT(*) AS rows_total,
COUNT(city) AS with_city,
COUNT(DISTINCT city) AS cities
FROM customers;
| rows_total | with_city | cities |
|---|---|---|
| 8 | 7 | 3 |
Common mistakes
- Mixing an aggregate with a normal column, like
SELECT name, MAX(price), withoutGROUP BY. Most databases reject it, and SQLite quietly picks a row. - Expecting
AVGto count NULLs as zero. It ignores them; useAVG(COALESCE(x, 0))if they should count. - Integer division: in some databases
AVGof integers orSUM(a) / COUNT(*)rounds down. Multiply by1.0to get decimals.
Practice Aggregate Functions interactively
Write real queries in your browser and get instant feedback in the lesson “COUNT, SUM, AVG” (Unit 4). New learners can start free from the first lesson.
Frequently asked questions
Can I filter on an aggregate?
Not in WHERE. Use HAVING, which runs after grouping.
What does SUM return when there are no rows?
NULL, not 0. Wrap it: COALESCE(SUM(x), 0).