Medium Aggregates and GROUP BY Employees database

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

Press Run to see your query's result, or Check answer to compare it with the expected result.

Expected result

department_idemployees
14

Rows can come in any order. Column names do not have to match.

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.

Want to try the query on MySQL or PostgreSQL? Open it in the SQL Online Compiler or SQLite Online.