Medium Aggregates and GROUP BY Employees database

Count per group with GROUP BY

Question

For each department_id, show the department id and the number of employees in it.

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
23
32
43

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

Hint

GROUP BY makes one group per department; COUNT(*) then counts each group.

Show the solution
solution.sql Run this code
SELECT department_id, COUNT(*) AS employees
FROM employees
GROUP BY department_id;

Why it works

GROUP BY department_id puts the rows into one bucket per department, and every aggregate in SELECT is calculated per bucket. You get one row per department.

Common mistake

Every column in SELECT must be either in GROUP BY or inside an aggregate. Adding name here would make no sense, since a group has many names.

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