SQL VISUALIZER

WHERE vs HAVING in SQL: What’s the Difference?

Both WHERE and HAVING filter — but at different stages. WHERE filters individual rows before they are grouped; HAVING filters whole groups after aggregates are computed.

▶ Open a WHERE + HAVING example in SQL Visualizer

The one-sentence rule

Why — it’s about order

SQL runs WHERE before GROUP BY, and HAVING after. So when WHERE runs, groups and their aggregates do not exist yet — which is exactly why you cannot filter on SUM(...) there. (Full sequence: SQL execution order.)

Both in one query

Keep only recent movies (a row filter), group by genre, then keep only the high-revenue genres (a group filter):

SELECT genre, SUM(revenue) AS total_revenue
FROM movies
WHERE year >= 2000          -- row filter: runs first
GROUP BY genre
HAVING SUM(revenue) > 1000  -- group filter: runs after aggregation
ORDER BY total_revenue DESC
WHERE trims rows up front; HAVING trims groups at the end.

The classic mistake

Writing WHERE SUM(revenue) > 1000 raises an error because aggregates are not available at the WHERE stage. Move it to HAVING.

A performance note

When a condition can go in WHERE, prefer it there: filtering rows before grouping means fewer rows to aggregate. Reserve HAVING for conditions that genuinely need the aggregate. See GROUP BY and HAVING for the grouping mechanics.

▶ Open a WHERE + HAVING example in SQL Visualizer