IntermediateWHERE & Filtering

Filter using HAVING with GROUP BY

The query

SQL
SELECT dept_id, COUNT(*) AS emp_count
FROM employees
GROUP BY dept_id
HAVING COUNT(*) > 5; -- Only depts with more than 5 employees
Tested against PostgreSQL 16

Note

HAVING filters AFTER grouping. WHERE filters BEFORE grouping. Common interview confusion!

Tables referenced