What is the difference between WHERE and HAVING in SQL?

WHERE and HAVING both filter data in a SQL query, but they act at different stages of query execution -- WHERE filters individual rows before grouping happens, while HAVING filters groups after GROUP BY has produced them.

Key Points

Example

To find departments with more than 5 employees, you group employees by department and then use HAVING COUNT(*) > 5, since COUNT(*) is an aggregate that only exists after grouping.

SELECT department_id, COUNT(*) AS emp_count
FROM employees
WHERE status = 'ACTIVE'
GROUP BY department_id
HAVING COUNT(*) > 5;

Interview Tip

A concise interview answer is

WHERE filters individual rows before grouping and can't use aggregate functions, while HAVING filters the groups produced by GROUP BY and can reference aggregates like COUNT() or SUM(). I typically use WHERE to cut down rows early for performance, then HAVING to filter on the aggregated result.

Last updated: 11 November 2026

Previous question: What is the difference between INNER JOIN and OUTER JOIN?

Next question: What is the difference between UNION and UNION ALL?

More SQL interview questions

All SQL questions