Filter groups with HAVING
Question
Show the department_id and the number of employees for departments that have more than 3 employees.
employeesid, name, salary, department_id, manager_id, hired_on
departmentsid, name, city
Your query
Ctrl+Enter to run
Result
Expected result
| department_id | employees |
|---|---|
| 1 | 4 |
Hint
WHERE filters rows before grouping; HAVING filters the groups after.
Show the solution
solution.sql
Run this code
SELECT department_id, COUNT(*) AS employees
FROM employees
GROUP BY department_id
HAVING COUNT(*) > 3;
Why it works
The count only exists after GROUP BY, so it cannot be used in WHERE. HAVING runs on the groups and keeps the ones with more than three people.
Common mistake
WHERE COUNT(*) > 3 gives an error ("misuse of aggregate"). Use WHERE for conditions on single rows and HAVING for conditions on groups.