Interview Questions/SQL/Second Highest Salary Per Department

Second Highest Salary Per Department

Preview mode. Log in to edit, run, submit, and save progress.

Medium

Description

You are given a table of staff members. Each staff member has a name, a department, and a salary. Write a SQL query to find the second highest distinct salary in each department. If a department does not have at least two distinct salary values, it should not appear in the result. Return the result ordered by department. Table: Staff

Column NameTypeDescription
idINTPrimary key
nameVARCHARStaff member name
deptVARCHARDepartment name
salaryINTAnnual salary

Database Schema (Inferred)

Staff

Column NameExample Value
id1
nameAlice
deptEng
salary100000

Example

Staff

idnamedeptsalary
1AliceEng100000
2BobEng90000
3CarolEng80000
4DaveSales70000
5EveSales70000
6FrankSales60000

Output

deptsecond_highest
Eng90000
Sales60000

Explanation:

In Eng, the max salary is 100000 so the second highest is 90000. In Sales, both Dave and Eve earn 70000 (the max), so the second distinct salary is 60000.

Approach hint

Start with a simple approach, explain the trade-off, then move toward a cleaner or more scalable solution.

Common mistake

Skipping assumptions, edge cases, or trade-offs can make an otherwise good answer feel incomplete.

SQL Editor
Loading...

Staff

idnamedeptsalary
1AliceEng100000
2BobEng90000
3CarolEng80000
4DaveSales70000
5EveSales70000
6FrankSales60000

Output

deptsecond_highest
Eng90000
Sales60000