Return the manager name with the most direct reports, and the count. Break ties alphabetically. Table definitions…
SQLLevel: IntermediateJoins and self-joins
Return the manager name with the most direct reports, and the count. Break ties alphabetically.
Table definitions (from the source exercise):
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: Join reports to managers, GROUP BY manager, ORDER BY count DESC LIMIT 1.
SELECT m.name, COUNT(*) AS reports
FROM employees e
JOIN employees m ON m.emp_id = e.manager_id
GROUP BY m.emp_id, m.name
ORDER BY reports DESC, m.name
LIMIT 1;
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