SQL Interview Questions · Question 03

Write a query to find the second-highest distinct salary?

Interview preparation resource from Gate Smashers.

Interview-ready answer

Use the maximum salary that is less than the overall maximum: SELECT MAX(salary) AS second_highest_salary FROM Employees WHERE salary < (SELECT MAX(salary) FROM Employees); This returns the second-highest distinct salary (NULL if fewer than two distinct salaries exist).

Employees
employee_idemployee_namedepartmentsalarymanager_id
101AaravEngineering95000105
102MeeraEngineering72000105
103KabirSales65000106
104IshaSales92000106
105RohanEngineering90000NULL
106NehaSales88000NULL
SQL querysql
SELECT MAX(salary) AS second_highest_salary
FROM Employees
WHERE salary < ( SELECT MAX(salary) FROM Employees );
Understand it clearly

Query (direct answer)

Find the second-highest distinct salary by selecting the maximum salary that is strictly less than the overall maximum salary. The query below implements this approach and returns NULL when fewer than two distinct salaries exist.

  • Query: See the SQL code block in Content Blocks for the exact statement.

How it works

The solution uses a subquery to determine the overall maximum salary, then the outer query finds the largest salary smaller than that value. This ensures the result is the second-highest distinct salary rather than a tied value equal to the maximum.

  • Inner query: Finds the highest salary: (SELECT MAX(salary) FROM Employees).
  • Outer query: Finds the maximum salary where salary is less than the value returned by the inner query.

Edge case

If the table contains fewer than two distinct salary values, the WHERE filter excludes all rows and the aggregate MAX returns NULL. That indicates no second-highest distinct salary exists.

  • Result when insufficient distinct salaries: NULL

When to prefer DENSE_RANK

Use DENSE_RANK (or similar window functions) when you need to return employee details along with the nth-highest salary or when requesting arbitrary ranks (e.g., 3rd highest). DENSE_RANK handles ties and makes it easy to select rows with a specific rank rather than only the scalar salary value.

  • Use-case: Return employee rows or nth-highest values; handle ties explicitly.