MintQueryStart free
← All guides

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

orders
order_idcustomeramount
101Ana50
102Ana30
103Ben20
104Chloe75
105Chloe5

HAVING: filter the groups

SELECT customer, COUNT(*) AS order_count
FROM orders
GROUP BY customer
HAVING COUNT(*) > 1
ORDER BY customer;
customerorder_count
Ana2
Chloe2

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;
customerorder_count
Ana2

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.

reviews
review_idproductstars
1Kettle5
2Kettle4
3Kettle2
4Grinder5
5Grinder3
6Scale4
7Scale5
8Mug2
9Mug1

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;
productgood_reviews
Kettle2
Scale2

MintQuery has 500+ exercises like this one, in lessons of a few minutes.

Start freeGet the app