Many rows, one number
An aggregate function turns many rows into one value.
A function takes input and gives back a result, like LOWER in chapter 1. An aggregate function reads many rows and gives back one value. COUNT and SUM are two of them.
Chapter 1 used COUNT on a whole table. This query uses COUNT and SUM together:
| order_id | customer_id | status | amount | order_date |
|---|---|---|---|---|
| 101 | 1 | paid | 40.00 | 2026-01-03 |
| 102 | 1 | paid | 25.00 | 2026-01-10 |
| 103 | 2 | refunded | 60.00 | 2026-01-11 |
| 104 | 3 | paid | 15.50 | 2026-01-15 |
| 105 | 3 | pending | NULL | 2026-01-20 |
| 106 | 4 | paid | 80.00 | 2026-01-21 |
SELECT COUNT(*) AS orders,
SUM(amount) AS total_amount
FROM orders;| orders | total_amount |
|---|---|
| 6 | 220.50 |
SUM skips order 105, because its amount is NULL. The total is 40 + 25 + 60 + 15.50 + 80.
What you will learn
Many business numbers are aggregates: orders per day, revenue per country, the share of paid orders. A small mistake gives a wrong number and no error message.
In this chapter, you learn to:
- Use COUNT, SUM, AVG, MIN and MAX, and know what they do with NULL.
- Make one result row for each group with GROUP BY.
- Remove groups with HAVING.
- Count different values, and count only some rows.
- Calculate a rate without a wrong answer or an error.
- Find the median, and check that a grouped result is right.
The examples use the same shop as chapter 1: customers, orders and order_items. They use PostgreSQL. We tell you when another database is different.
