Learn SQL: HAVING
Filtering groups with HAVING
Lien's last question: "Which countries should I aim for next year? Only the ones that really brought something in." For that you don't filter the rows, you filter the groups.
HAVING filters groups
WHERE filters rows, HAVING filters groups. It comes after GROUP BY and can use aggregate functions: here only the countries with more than five rentals are left.
SELECT customer_country, COUNT(*) AS rentals FROM rentals GROUP BY customer_country HAVING COUNT(*) > 5| customer_country | rentals |
|---|---|
| Belgium | 10 |
| Germany | 6 |
| Netherlands | 9 |
WHERE before, HAVING after grouping
The database works in this order: WHERE throws rows away, GROUP BY makes groups, HAVING throws groups away, ORDER BY sorts. That's why a function like SUM in WHERE gives an error: the groups don't exist yet at that point.
You can use them together. Here: only August, and only the bike types that brought in more than 100 euros then.
SELECT bike_type, SUM(amount) AS revenue FROM rentals WHERE start_date BETWEEN '2025-08-01' AND '2025-08-31' GROUP BY bike_type HAVING SUM(amount) > 100| bike_type | revenue |
|---|---|
| city bike | 101 |
| e-bike | 267 |
Try it yourself
Which brands have more than two bikes? Show the brand and the number.
Ready for more?
The full lesson has 6 exercises, from easy to challenging, with hints, points and a streak you can build.
Start the lesson