As reported: Qualcomm Staff Software Engineer, round 1 — databases part (2026): find the employees with the second-highest salary in each department, followed by a follow-up question.
Tables:
employee(id INT PRIMARY KEY, name VARCHAR, salary INT, department_id INT)
department(id INT PRIMARY KEY, name VARCHAR)
Write a query returning department_name, employee_name, salary for every employee whose salary is the second-highest distinct salary in their department.
Example
employee department
id | name | salary | department_id id | name
1 | Asha | 90000 | 1 1 | Engineering
2 | Ben | 80000 | 1 2 | Sales
3 | Chen | 80000 | 1
4 | Dana | 70000 | 1
5 | Eli | 60000 | 2
6 | Fay | 50000 | 2
7 | Gus | 40000 | 3
Result:
Engineering | Ben | 80000
Engineering | Chen | 80000
Sales | Fay | 50000
Clarifications
- Ties share a rank: if two people earn the top salary, the second-highest is the next lower distinct salary.
- Departments with only one distinct salary produce no row.