Interview Questions/SQL/Nth Highest Distinct Salary

Nth Highest Distinct Salary

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

Medium

Description

You are given an Employees table with salaries. Write a SQL query to find the 3rd highest distinct salary. If fewer than 3 distinct salary values exist, return an empty result. Return a single column named third_highest_salary. Table: Employees

Column NameTypeDescription
idINTPrimary key
nameVARCHAREmployee name
salaryINTAnnual salary

Database Schema (Inferred)

Employees

Column NameExample Value
id1
nameAlice
salary90000

Example

Employees

idnamesalary
1Alice90000
2Bob85000
3Carol85000
4Dave80000
5Eve75000

Output

third_highest_salary
80000

Explanation:

Distinct salaries in descending order: 90000, 85000, 80000, 75000. The 3rd distinct value is 80000. Note that 85000 appears twice but counts once.

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...

Employees

idnamesalary
1Alice90000
2Bob85000
3Carol85000
4Dave80000
5Eve75000

Output

third_highest_salary
80000