Helix Systems' HR director is reviewing departmental capacity to identify teams that may need additional headcount.
Write a query to return the department ID and employee count for every department with more than five employees.
Assumptions:
- The
employeestable contains every active and former employee at Helix Systems. department_idlinks each employee to their department.- The threshold is on the per-department headcount.
Output:
- One row per qualifying department, with columns
department_idandemployee_count.
Schema · hr 4 tables
Run previews · Check grades
Write a query, then run it to see results here.
Worked solution Try it yourself first
SELECT
department_id,
COUNT(*) AS employee_count
FROM
employees
GROUP BY
department_id
HAVING
COUNT(*) > 5 The shape
The headcount-by-department report comes from grouping employees on department_id and counting the rows in each group. HAVING COUNT(*) > 5 keeps only the departments large enough for the HR director's review — department 1 with 17 employees, 3 with 11, 2 with 7, and the two six-person teams.
Clause by clause
SELECT department_id, COUNT(*) AS employee_countreturns the grouping column with its per-group row count.COUNT(*)here means "every employee that landed in this department's group" — column values are not consulted, only row existence.FROM employeesis the source set: every active and former Helix Systems employee.GROUP BY department_idpartitions the rows into one group per department. The working set after this clause has one row per distinctdepartment_id.HAVING COUNT(*) > 5filters those department rows by their headcount. Departments with five or fewer employees drop out; six or more survive.
Why this and not WHERE COUNT(*) > 5
The per-group count doesn't exist until GROUP BY has finished partitioning. WHERE runs earlier, when the only thing in scope is a single employee row. There is no count to compare against at that stage. HAVING is the only clause that runs after grouping, which makes it the only place a COUNT(*) threshold can be checked.
You practiced the canonical GROUP BY + HAVING shape against a count threshold. Any "groups with at least N members" question takes this exact form — GROUP BY builds the groups, HAVING COUNT(*) > N filters them.