Sub topic 1
Summarizing a table with aggregate functions
Prerequisites
This chapter assumes you can write SELECT, FROM, WHERE and ORDER BY, that you understand tables as rows and columns, and that you know NULL marks a missing value. The examples use an orders table with the columns order_id, customer_id, amount and shipped_at.
Aggregate functions
An aggregate function takes many input values and returns one value. The five standard aggregates are COUNT, SUM, AVG, MIN and MAX. Without a GROUP BY clause, they treat the whole table as one group:
SELECT COUNT(*) AS order_count,
SUM(amount) AS total_amount,
AVG(amount) AS avg_amount,
MIN(amount) AS smallest,
MAX(amount) AS largest
FROM orders;This query returns exactly one row.
How aggregates treat NULL
Aggregates skip NULL inputs. SUM, AVG, MIN and MAX ignore them. AVG divides by the number of non-NULL values, so a NULL row does not count as zero.
COUNT(*), COUNT(column) and COUNT(DISTINCT)
Three forms of COUNT answer different questions:
| Expression | What it counts |
|---|---|
| `COUNT(*)` | Every row |
| `COUNT(column)` | Rows where that column is not NULL |
| `COUNT(DISTINCT column)` | Unique non-NULL values in that column |
SELECT COUNT(*) AS all_orders,
COUNT(shipped_at) AS shipped_orders,
COUNT(DISTINCT customer_id) AS distinct_customers
FROM orders;Grouping rows with GROUP BY
GROUP BY splits rows into groups, one for each distinct value of the grouping column. Each aggregate then runs separately inside every group:
SELECT customer_id,
COUNT(*) AS order_count,
SUM(amount) AS total_amount
FROM orders
GROUP BY customer_id
ORDER BY total_amount DESC;Each column in the SELECT list must either appear in GROUP BY or sit inside an aggregate. Selecting shipped_at alongside customer_id in the query above would fail, because one customer can have many different shipment dates.
Exercise
Using the orders table, how many rows does SELECT customerid, COUNT(*) FROM orders GROUP BY customerid return if 4 customers have placed orders and 2 more customers have never ordered?
Show answer
Four rows. GROUP BY produces one row per distinct customer_id present in orders. Customers with no orders never appear in the table, so they are not counted.