Lesson 216 of 296
GROUP BY, HAVING and aggregates
What you will learn
- Aggregate functions
- Grouping rows with GROUP BY
- Filtering groups with HAVING
- WHERE vs HAVING
- COUNT(*) vs COUNT(column), and a LEFT JOIN trap
- FILTER for conditional aggregates
On this page
Aggregate functions
An aggregate turns many rows into one value:
| Function | Returns |
|---|---|
COUNT(*) | Number of rows |
COUNT(column) | Number of non-NULL values in that column |
COUNT(DISTINCT column) | Number of different non-NULL values |
SUM, AVG, MIN, MAX | Total, average, smallest, largest (all ignore NULLs) |
STRING_AGG(name, ', '), ARRAY_AGG(...) | Join values into one string or array |
SELECT COUNT(*) AS customers, COUNT(city) AS with_city FROM customers;| customers | with_city |
|---|---|
| 5 | 4 |
COUNT(city) skips Dara's NULL city.
GROUP BY
GROUP BY splits rows into groups with the same value, then calculates an aggregate per group:
SELECT status, COUNT(*) AS orders FROM orders GROUP BY status ORDER BY status;| status | orders |
|---|---|
| cancelled | 1 |
| paid | 4 |
| pending | 1 |
The rule: every column in SELECT must either be in GROUP BY or inside an aggregate. SELECT status, ordered_at, COUNT(*) ... GROUP BY status is an error: which ordered_at would it show for a group of four orders? (PostgreSQL allows other columns of a table when you group by that table's primary key, as below.)
Total spent per customer on paid orders:
SELECT c.name,
COUNT(DISTINCT o.id) AS paid_orders,
SUM(oi.quantity * oi.unit_price_pence) AS spent_pence
FROM customers c
JOIN orders o ON o.customer_id = c.id AND o.status = 'paid'
JOIN order_items oi ON oi.order_id = o.id
GROUP BY c.id, c.name
ORDER BY spent_pence DESC;| name | paid_orders | spent_pence |
|---|---|---|
| Chen Li | 2 | 7297 |
| Aisha Khan | 2 | 5247 |
COUNT(DISTINCT o.id) is needed because the join to order_items gives one row per item (fan-out, Lesson 215); COUNT(*) would count items, not orders.
HAVING
WHERE filters rows before grouping. HAVING filters groups after grouping, so it can use aggregates:
SELECT c.name, SUM(oi.quantity * oi.unit_price_pence) AS spent_pence
FROM customers c
JOIN orders o ON o.customer_id = c.id
JOIN order_items oi ON oi.order_id = o.id
WHERE o.status = 'paid'
GROUP BY c.id, c.name
HAVING SUM(oi.quantity * oi.unit_price_pence) > 4000
ORDER BY spent_pence DESC;| name | spent_pence |
|---|---|
| Chen Li | 7297 |
| Aisha Khan | 5247 |
Interview answer: "WHERE filters rows and cannot use aggregates; HAVING filters groups and can." Put conditions that do not need aggregates in WHERE: fewer rows to group means a faster query.
Several aggregates per group
SELECT p.category,
SUM(oi.quantity) AS units,
ROUND(AVG(oi.unit_price_pence)) AS avg_price_pence,
MIN(oi.unit_price_pence) AS cheapest,
MAX(oi.unit_price_pence) AS dearest
FROM order_items oi
JOIN products p ON p.id = oi.product_id
JOIN orders o ON o.id = oi.order_id
WHERE o.status <> 'cancelled'
GROUP BY p.category
ORDER BY units DESC;| category | units | avg_price_pence | cheapest | dearest |
|---|---|---|---|---|
| Stationery | 6 | 717 | 450 | 1250 |
| Kitchen | 4 | 899 | 899 | 899 |
| Home | 2 | 2999 | 2999 | 2999 |
The LEFT JOIN COUNT trap
"How many orders does each customer have, including customers with none?"
SELECT c.name, COUNT(o.id) AS orders
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.name
ORDER BY c.id;| name | orders |
|---|---|
| Aisha Khan | 2 |
| Ben Smith | 1 |
| Chen Li | 2 |
| Dara Patel | 1 |
| Eve Jones | 0 |
If you write COUNT(*) instead of COUNT(o.id), Eve gets 1, because her LEFT JOIN row exists (with NULLs). COUNT(o.id) counts only non-NULL order IDs. A favourite "spot the bug" question.
Conditional aggregates with FILTER
SELECT COUNT(*) FILTER (WHERE status = 'paid') AS paid,
COUNT(*) FILTER (WHERE status <> 'paid') AS not_paid,
SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) AS cancelled
FROM orders;| paid | not_paid | cancelled |
|---|---|---|
| 4 | 2 | 1 |
FILTER is PostgreSQL (and the SQL standard); the SUM(CASE ...) form works in every database.
How to say it in an interview
"Aggregates like COUNT, SUM, AVG, MIN and MAX collapse rows into one value and ignore NULLs, except COUNT star, which counts rows. GROUP BY computes them per group, and every selected column must be grouped or aggregated. WHERE filters rows before grouping and cannot use aggregates; HAVING filters groups after. Two traps: joins fan out rows, so I use COUNT DISTINCT or pre-aggregate, and after a LEFT JOIN I count a column from the right table, not star, so customers without orders get zero."
Key words
| Word | Meaning |
|---|---|
| Aggregate function | Calculates one value from many rows |
| GROUP BY | Splits rows into groups for aggregation |
| HAVING | Filters groups after aggregation |
| COUNT(*) vs COUNT(col) | Counts rows vs counts non-NULL values |
| FILTER | Applies a condition to one aggregate |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.