What is the difference between WHERE and HAVING in SQL, and when must you use HAVING?
WHERE filters individual rows before any grouping occurs; HAVING filters groups after GROUP BY is evaluated. You must use HAVING when the filter condition references an aggregate function like SUM or COUNT.
How to think about it
The difference comes down to timing in SQL’s execution order. WHERE fires on raw rows before any grouping. HAVING fires on groups after aggregation. You cannot swap them arbitrarily — the engine enforces this with an error if you put an aggregate in WHERE.
The execution order
WHERE sees individual rows. At HAVING time, groups already exist and aggregate values are available.
Rule of thumb
- Filter on a raw column value? Use
WHERE. - Filter on an aggregate (
COUNT,SUM,AVG, etc.)? You must useHAVING.
Both in the same query
Push filters as early as possible
Both WHERE and HAVING produce the same final result when applied to a non-aggregate column — but WHERE lets the engine skip rows before doing the expensive grouping work. On large tables this difference is significant.