WHERE filters individual rows before they are grouped, and HAVING filters the groups after GROUP BY has formed them.
WHERE runs first, so it cannot use aggregate functions such as COUNT or AVG, because the groups do not exist yet. HAVING runs after grouping, so it can test those results, such as keeping only departments with more than five employees.
A condition that needs no aggregate belongs in WHERE. Filtering early means fewer rows reach the grouping step, which makes the query cheaper.
-- WHERE filters before grouping
SELECT department, COUNT(*)
FROM employees
WHERE salary > 50000
GROUP BY department;
-- HAVING filters after grouping
SELECT department, COUNT(*)
FROM employees
GROUP BY department
HAVING COUNT(*) > 5;
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
Why there's no diagram: “”
The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓
The diagram below the answer is the concept . Jump to it ↓