Write a query to list departments that have more than 5 employees.
Group by department and filter groups with HAVING COUNT(*) > 5. WHERE cannot be used because the count exists only after grouping.
Explain it simply
Count heads in each department, then keep only the departments whose count passes the bar. Counting must happen first, so the filter on the count goes in HAVING.
Line by line
Table employees(id, name, dept_id).
SELECT dept_id, COUNT(*) AS headcount
FROM employees
GROUP BY dept_id
HAVING COUNT(*) > 5;GROUP BY dept_idforms one group per department.COUNT(*)counts the rows in each group.HAVING COUNT(*) > 5removes groups of 5 or fewer.
To show the department name, join to departments and group by the name as well:
SELECT d.name, COUNT(*) AS headcount
FROM employees e
JOIN departments d ON d.id = e.dept_id
GROUP BY d.id, d.name
HAVING COUNT(*) > 5;An employee with a NULL dept_id would form a NULL group in the first query.
Complexity
Time: O(n) with hash aggregation, or O(n log n) if the database sorts to group. Space: O(g) for g groups.
What to say in the interview
"I group by department and use HAVING for the condition on the aggregate. WHERE filters rows before grouping, HAVING filters groups after."