HomeInterview QuestionsWrite a fresh query to fetch the second highest sa…

Write a fresh query to fetch the second highest salary from the employees table.

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

💡 Model Answer

A concise way to get the second highest salary is to use a window function that ranks salaries in descending order. The query looks like this:

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

Explanation:

  1. The inner SELECT assigns a dense rank to each distinct salary, with 1 for the highest, 2 for the second highest, etc.
  2. The outer query filters for rank 2, returning the second highest salary.

If your database does not support window functions, you can use a subquery with LIMIT/OFFSET:

sql
SELECT DISTINCT salary
FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET 1;

Both approaches run in O(n) time and use minimal extra space. They handle duplicate salaries correctly because DENSE_RANK treats equal values as the same rank. This solution is portable across most SQL engines and is suitable for interview scenarios where you need to demonstrate knowledge of ranking and subqueries.

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