Programming

What is the difference between SQL's WHERE and HAVING clauses?

Short answer

WHERE filters individual rows before any grouping happens, while HAVING filters groups after a GROUP BY has aggregated the data.

Both clauses filter query results, but they operate at different stages of query execution.

WHERE

Applied first, before grouping or aggregation — it filters raw rows based on column values, and can't reference aggregate functions like COUNT() or SUM() directly.

HAVING

Applied after GROUP BY has combined rows into groups — it filters those groups, typically based on an aggregate condition, like only showing departments with more than 10 employees.

Example

SELECT department, COUNT(*) AS emp_count
FROM employees
WHERE status = 'active'
GROUP BY department
HAVING COUNT(*) > 10;

Here, WHERE filters to only active employees first, then HAVING filters the resulting department groups down to ones with more than 10 people.

Last reviewed: September 2026