HomeInterview QuestionsHow do you fetch the second highest value in a tab…

How do you fetch the second highest value in a table using a subquery?

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

💡 Model Answer

One common approach is to use a subquery that selects the maximum value less than the overall maximum:

sql
SELECT MAX(col) AS second_highest
FROM my_table
WHERE col < (SELECT MAX(col) FROM my_table);

Alternatively, you can use window functions for clarity and flexibility:

sql
SELECT col
FROM (
  SELECT col, ROW_NUMBER() OVER (ORDER BY col DESC) AS rn
  FROM my_table
) t
WHERE rn = 2;

Both queries run in O(n) time and O(1) additional space (ignoring the temporary row number column). The window‑function version is often preferred for readability and when you need more than just the second highest value.

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