Nth Highest Salary Per Department

A medium SQL interview practice problem on DataDriven. Write the query and run it against a real database, with instant feedback.

Domain
SQL
Difficulty
medium
Seniority
L5

Problem

For each department, find the employee with the third-highest salary. If a department has fewer than 3 employees, exclude it. Return department, employee name, and their salary.

Third place in every department.

Tables

employees

Columns: employee_id INTEGER, emp_name TEXT, department TEXT, salary REAL, manager_id INTEGER, hire_date TEXT, user_id INTEGER

employees: 10 of 200 rows
employee_idemp_namedepartmentsalarymanager_idhire_dateuser_id
1Alice ChenEngineering55731NULL2021-02-02100
2Bob MartinezProduct61462NULL2022-03-03197
3Carol WuDesign67193NULL2023-04-04294
4David KimMarketing72924NULL2024-05-05391
5Eve JohnsonSales78655NULL2025-06-06488
6Frank PatelHR84386NULL2026-07-07585
7Grace LeeFinance55117NULL2020-08-08682
8Hank BrownOperations60848NULL2021-09-09779
9Iris DavisData66579NULL2022-10-10876
10Jake WilsonLegal72310NULL2023-11-11973

Expected output

First 5 of 20 rows
departmentemp_namesalary
DataXan Sullivan127369
DataXan Sullivan127369
DesignWes Barnes118363
DesignWes Barnes118363
EngineeringOak Russell116521

Worked solution and explanation

Why this problem exists in real interviews

Against the employees table, dense ranking on emp_name values is the key operation. Interviewers favor this in mid-level screens because it exposes whether candidates handle ties, NULLs, and ordering edge cases correctly.


Break down the requirements

Step 1: Rank employees within each department

DENSE_RANK() OVER (PARTITION BY department ORDER BY salary DESC) assigns rank 1 to the highest salary in each department, with ties sharing a rank.

Step 2: Filter to rank 3

Wrap in a subquery and WHERE rnk = 3 to get the third-highest salary per department.

Step 3: Exclude small departments

Departments with fewer than 3 employees will have no row at rank 3, so they naturally drop out. Alternatively, add a HAVING COUNT(*) >= 3 guard.


The solution

Window rank then filter to position 3
SELECT department, emp_name, salary
FROM (
    SELECT
        department,
        emp_name,
        salary,
        DENSE_RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS rnk
    FROM employees
) ranked
WHERE rnk = 3

Common follow-up questions