Blog · Guide

HAVING vs WHERE in SQL: When to Filter Groups

WHERE filters rows before grouping. HAVING filters groups after aggregation. Same shop examples for both.

rows Austin Milan Austin Milan GROUP BY Austin → COUNT = 2 Milan → COUNT = 2
GROUP BY buckets rows that share a value, then aggregates each bucket.

WHERE first, HAVING later

WHERE removes rows before groups form. HAVING removes groups after COUNT/SUM exist.

SELECT city, COUNT(*) AS n
FROM customers
GROUP BY city
HAVING COUNT(*) >= 2;

You can’t put COUNT(*) in WHERE — it doesn’t exist yet at row-filter time.

Try it yourself

The fastest way to lock this in is a short drill on the same Northstar Market tables.

Practice HAVING

Related guides