EasyConcept

What is the difference between WHERE and HAVING in SQL?

Technology:
SQL
Experience:
Intern,
Junior
Topics:
SQL

Quick answer

WHERE filters individual rows before grouping, while HAVING filters groups after GROUP BY, so only HAVING can use aggregate functions like COUNT or SUM.

Detailed explanation

SQL processes a query in a logical order: FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY. Because WHERE runs before grouping, the aggregates do not exist yet. HAVING runs after grouping, so it can test them.

Put every condition that does not need an aggregate in WHERE. It reduces the rows before grouping, which is faster than filtering the groups afterwards.

Example

sql
SELECT department, COUNT(*) AS staff, AVG(salary) AS avg_salary
FROM employees
WHERE status = 'active'          -- filters rows first
GROUP BY department
HAVING COUNT(*) >= 5;            -- filters groups after aggregation