Skip to content
Quantoros

Return the top 5 highest paid employees per department: departmentid, name, salary. Break salary ties by name. Table…

SQLLevel: IntermediateRanking and Top-N

Return the top 5 highest paid employees per department: department_id, name, salary. Break salary ties by name.

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: ROW_NUMBER partitioned by department, rn <= 5.

SELECT department_id, name, salary
FROM (
  SELECT e.*, ROW_NUMBER() OVER (PARTITION BY department_id
                                 ORDER BY salary DESC, name) AS rn
  FROM employees e
) x
WHERE rn <= 5;

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

Related questions