FresherTechnicalSQL
What is the difference between WHERE and HAVING?
Try answering first
Model answer
WHERE filters individual rows before grouping. HAVING filters groups after aggregation, so it can use aggregate functions such as COUNT or SUM, which WHERE cannot.
SELECT customer_id, COUNT(*) AS orders, SUM(total) AS spent
FROM orders
WHERE status = 'paid' -- row filter, runs first
GROUP BY customer_id
HAVING SUM(total) > 1000; -- group filter, runs after
The order is: FROM, WHERE, GROUP BY, aggregates, HAVING, SELECT, ORDER BY. That is why WHERE SUM(total) > 1000 is an error: when WHERE runs, the sums do not exist yet.
Put every condition that does not need an aggregate in WHERE, not in HAVING. It removes rows early so fewer rows are grouped, and it lets the database use an index.
-- better: filter before grouping
WHERE customer_id = 7
-- worse: same filter after grouping
HAVING customer_id = 7
Remember: WHERE filters rows, HAVING filters groups.
Key points
- WHERE filters rows before grouping
- HAVING filters groups and can use aggregates
- Aggregates are not allowed in WHERE
- Non-aggregate conditions belong in WHERE for speed
Likely follow-ups
- Can you use a column alias in HAVING?
Common mistakes
- Writing WHERE COUNT(*) > 1
- Filtering plain columns in HAVING and grouping more rows than needed