What is the difference between WHERE and HAVING?
SQLLevel: FoundationFundamentals (Easy)
What is the difference between WHERE and HAVING?
Hints
- Define one output row and the source-table keys.
- Check duplicates, NULLs and the order of filtering and aggregation.
Answer
WHERE filters rows before grouping and aggregation. HAVING filters after aggregation, so you can use it to filter on aggregate values.
-- WHERE: filters before GROUP BY
SELECT department, COUNT(*) AS emp_count
FROM employees
WHERE active = true
GROUP BY department;
-- HAVING: filters after GROUP BY
SELECT department, COUNT(*) AS emp_count
FROM employees
GROUP BY department
HAVING COUNT(*) > 10;
-- Both together
SELECT department, COUNT(*) AS emp_count
FROM employees
WHERE active = true
GROUP BY department
HAVING COUNT(*) > 10;
Common wrong answer: "HAVING is just WHERE for GROUP BY" — partially true, but misses the execution order, which is what matters for understanding behavior and performance.
Source and licence: SQL Interview Questions — Arda Kocadoru · MIT