Module 9 · SQL for Data Analysis
HAVING
Filter groups after they're calculated, such as customers with more than 30 shipments.
About 20 minutes
The problem
Harbourline is planning a loyalty discount for its most active customers. The rule the sales director proposes is simple:
"Anyone who booked more than 30 shipments in 2025."
You can count shipments per customer with GROUP BY. But you can't write WHERE COUNT(*) > 30, because WHERE runs before the counting happens.
The concept
HAVING filters groups, after the aggregates are calculated. WHERE filters rows, before grouping.
WHERE | HAVING | |
|---|---|---|
| Filters | individual rows | groups |
| Runs | before GROUP BY | after GROUP BY |
Can use aggregates like COUNT(*) | no | yes |
The full order of clauses is now:
SQL
SELECT … FROM … WHERE … GROUP BY … HAVING … ORDER BY … LIMIT …Example
SELECT
customer_id,
COUNT(*) AS shipments_2025
FROM shipments
WHERE booking_date BETWEEN '2025-01-01' AND '2025-12-31'
GROUP BY customer_id
HAVING COUNT(*) > 30
ORDER BY shipments_2025 DESC;Walkthrough
The database works through it in this order:
FROM shipmentstakes all shipments.WHERE …keeps only 2025 bookings. This is a row filter.GROUP BY customer_idbuilds one group per customer.COUNT(*)counts each group.HAVING COUNT(*) > 30keeps only groups with more than 30 shipments. This is a group filter.ORDER BYsorts what's left.
Use both together when you need both kinds of filter. Here, routes that are expensive on average and busy enough for the average to mean something:
SELECT
route_id,
COUNT(*) AS shipments,
ROUND(AVG(freight_charge)) AS avg_charge
FROM shipments
WHERE status <> 'Cancelled'
GROUP BY route_id
HAVING COUNT(*) >= 50
ORDER BY avg_charge DESC;Practice
Practice
Which customers booked more than 40 shipments in total, across all dates? Show customer_id and the number of shipments.
Ctrl + Enter to run. Tab indents; press Esc then Tab to leave the editor.
Challenge
Challenge · optional
Find the industries where Harbourline has at least 12 customers. Show industry and the number of customers, most customers first, then industry A to Z.
Ctrl + Enter to run. Tab indents; press Esc then Tab to leave the editor.
Check your understanding
Answer every question to check.