Interview Questions/SQL/Second Highest Salary per Department (DENSE_RANK)

Second Highest Salary per Department (DENSE_RANK)

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

Medium

Description

You are given a table of employees. Each employee belongs to a department and has a salary. Write a SQL query to find the employee(s) with the second-highest salary in each department. Use DENSE_RANK so that ties at rank 1 do not skip rank 2. If a department has fewer than two distinct salary levels, it should not appear in the result. Return department, employee name, and salary ordered by department. Table: Staff

Column NameTypeDescription
idINTPrimary key
nameVARCHAREmployee name
departmentVARCHARDepartment name
salaryINTAnnual salary

Database Schema (Inferred)

Staff

Column NameExample Value
id1
nameAlice
departmentEng
salary95000

Example

Staff

idnamedepartmentsalary
1AliceEng95000
2BobEng90000
3CarolEng85000
4DaveSales70000
5EveSales70000
6FrankSales60000
7GraceHR55000

Output

departmentnamesalary
EngBob90000
SalesFrank60000

Explanation:

In Eng, Bob has the 2nd highest salary. In Sales, Eve and Dave tie for 1st (DENSE_RANK=1), so Frank at 60000 is rank 2. HR only has one employee - excluded.

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

idnamedepartmentsalary
1AliceEng95000
2BobEng90000
3CarolEng85000
4DaveSales70000
5EveSales70000
6FrankSales60000
7GraceHR55000

Output

departmentnamesalary
EngBob90000
SalesFrank60000