HomeInterview QuestionsIn SQL code, how would you write a query to find t…

In SQL code, how would you write a query to find the second highest salary?

🟡 Medium Coding Junior level
1Times asked
Jul 2026Last seen
Jul 2026First seen

💡 Model Answer

To find the second highest salary in a table, you can use a subquery or a window function. Using a subquery:

sql
SELECT MAX(salary) AS second_highest
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);

This returns the largest salary that is less than the overall maximum. If there are duplicate top salaries, this still works because it excludes all rows equal to the maximum. Alternatively, with a window function:

sql
SELECT salary
FROM (
  SELECT salary,
         DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk
  FROM employees
) AS ranked
WHERE rnk = 2;

Both approaches run in O(n) time, scanning the table once. The window‑function version is more flexible if you need to retrieve additional columns or handle ties. Choose the one that aligns with your database’s performance characteristics.

This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.

🎤 Get questions like this answered in real-time

Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.

Get Assisting AI — Starts at ₹500