Return every departmentname with its employee count, INCLUDING departments with zero employees, largest first then…
SQLLevel: IntermediateAnti-joins and missing data
Return every department_name with its employee count, INCLUDING departments with zero employees, largest first then name.
Table definitions (from the source exercise):
CREATE TABLE departments(department_id INTEGER PRIMARY KEY, department_name TEXT, created_date TEXT);
CREATE TABLE employees(emp_id INTEGER PRIMARY KEY, name TEXT, department_id INTEGER, manager_id INTEGER, salary INTEGER, hire_date TEXT, job_title TEXT, gender TEXT);
Hints
- Define one output row and the source-table keys.
- Check duplicates, NULLs and the order of filtering and aggregation.
Answer
Approach: LEFT JOIN and COUNT the employee key (not COUNT(*)).
SELECT d.department_name, COUNT(e.emp_id) AS headcount
FROM departments d
LEFT JOIN employees e ON e.department_id = d.department_id
GROUP BY d.department_id, d.department_name
ORDER BY headcount DESC, d.department_name;
The source uses SQLite with a MySQL compatibility layer. Date and string functions are dialect dependent; the query is preserved as published.
Source and licence: SQL Practice Lab — Ebrahim Sharifi · MIT