WHERE vs HAVING in SQL — What's the Difference?
WHERE filters individual rows before grouping; HAVING filters groups after GROUP BY and aggregation. Learn when SQL requires each one.
Published September 19, 2026
WHERE filters individual rows before grouping; HAVING filters groups after GROUP BY and aggregation. Use WHERE for row conditions and HAVING for conditions on COUNT, SUM and other aggregates.
The concept
SQL runs in a logical order: FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY. WHERE sees raw rows so it cannot reference aggregates; HAVING runs after the groups exist.
Filtering early with WHERE is faster because fewer rows get grouped.
Order of evaluation
- FROM orders — read the table
- WHERE status = 'paid' — drop rows
- GROUP BY customer_id — build groups
- HAVING SUM(total) > 100 — drop groups
Practical examples
Both together
SELECT customer_id, SUM(total) AS spent
FROM orders
WHERE status = 'paid'
GROUP BY customer_id
HAVING SUM(total) > 100;Error: aggregate in WHERE
SELECT customer_id FROM orders
WHERE COUNT(*) > 5 -- invalid
GROUP BY customer_id;Fixed
SELECT customer_id FROM orders
GROUP BY customer_id
HAVING COUNT(*) > 5;Common mistakes
- Using HAVING for plain row filters that WHERE could do faster.
- Using aggregates in WHERE.
- Referencing a SELECT alias in WHERE (allowed in HAVING in MySQL only).
Key takeaways
- WHERE = rows before grouping, HAVING = groups after.
- Aggregates only work in HAVING.
- Filter with WHERE first for speed.
FAQ
Can I use HAVING without GROUP BY?
Yes, the whole result is treated as one group, but it is rare.
Which is faster?
WHERE, because it reduces rows before the grouping work.