SQL · Pattern 5 — Grouping
HAVING
WHERE filters individual rows before grouping; HAVING filters the groups themselves after aggregation.
Source data — Pattern 5: Grouping
All queries run against the shared employees table (see schema.sql). This pattern needs two new columns — city (topic 30) and job_role (topic 31) — and enough rows in one department to actually cross a "more than 5" threshold (topic 29), so IT grows from 2 employees to 7.

What it does
WHERE filters individual rows before grouping; HAVING filters the groups themselves after aggregation. That's why HAVING can reference COUNT(*) or SUM(...) directly, while WHERE can't — the aggregate doesn't exist yet at the point WHERE runs.
Problem
Find departments having more than 5 employees.
SELECT department_id,
COUNT(*) AS employee_count
FROM employees
GROUP BY department_id
HAVING COUNT(*) > 5;
Result
