WHERE vs HAVING: which one filters what?
WHERE filters rows before they are grouped. HAVING filters the groups after. A condition about one row's own value, like its amount, goes in WHERE. A condition about a whole group, like a COUNT or a SUM, goes in HAVING.
How it usually happens
Someone asks which customers ordered more than once. Filtering means WHERE, so you write WHERE COUNT(*) > 1, and the database refuses. In PostgreSQL the message is "aggregate functions are not allowed in WHERE". The count does not exist yet when WHERE runs, because the rows have not been grouped.
The table
| order_id | customer | amount |
|---|---|---|
| 101 | Ana | 50 |
| 102 | Ana | 30 |
| 103 | Ben | 20 |
| 104 | Chloe | 75 |
| 105 | Chloe | 5 |
HAVING: filter the groups
SELECT customer, COUNT(*) AS order_count
FROM orders
GROUP BY customer
HAVING COUNT(*) > 1
ORDER BY customer;
| customer | order_count |
|---|---|
| Ana | 2 |
| Chloe | 2 |
The orders are grouped by customer first. Then HAVING keeps the groups with more than one order. Ben has one, so Ben is out.
WHERE and HAVING in the same query
Now the question changes: which customers have more than one order of 10 or more?
SELECT customer, COUNT(*) AS order_count
FROM orders
WHERE amount >= 10
GROUP BY customer
HAVING COUNT(*) > 1
ORDER BY customer;
| customer | order_count |
|---|---|
| Ana | 2 |
WHERE runs first and removes Chloe's order of 5. That leaves Chloe with one order, so her group fails the HAVING. The same two words, in a different place, give a different answer.
The order the database works in
FROM, then WHERE, then GROUP BY, then HAVING, then SELECT, then ORDER BY. That order is the whole explanation. WHERE comes before the groups exist, and HAVING comes after.
Rule to remember: if the condition has COUNT, SUM, AVG, MIN or MAX in it, it goes in HAVING. Everything else goes in WHERE, which also keeps the query faster, since fewer rows get grouped.
Try it yourself
Different table, same idea. A shop collects star ratings and wants to feature its best products.
| review_id | product | stars |
|---|---|---|
| 1 | Kettle | 5 |
| 2 | Kettle | 4 |
| 3 | Kettle | 2 |
| 4 | Grinder | 5 |
| 5 | Grinder | 3 |
| 6 | Scale | 4 |
| 7 | Scale | 5 |
| 8 | Mug | 2 |
| 9 | Mug | 1 |
The shop wants the products with at least two reviews of 4 stars or more, as product and good_reviews, sorted by product. The query below counts every review, good or bad. Fix it.
Hint
The stars belong to one review, not to a group. Which clause filters single rows?
Show solution
SELECT product, COUNT(*) AS good_reviews
FROM reviews
WHERE stars >= 4
GROUP BY product
HAVING COUNT(*) >= 2
ORDER BY product;| product | good_reviews |
|---|---|
| Kettle | 2 |
| Scale | 2 |
MintQuery has 500+ exercises like this one, in lessons of a few minutes.
Start freeGet the app