HomeInterview QuestionsHow do you find both the second highest and second…

How do you find both the second highest and second lowest values in a dataset?

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

💡 Model Answer

You can use window functions or subqueries. With window functions: SELECT DISTINCT value FROM (SELECT value, DENSE_RANK() OVER (ORDER BY value DESC) AS dr_desc, DENSE_RANK() OVER (ORDER BY value ASC) AS dr_asc FROM table) t WHERE dr_desc = 2 OR dr_asc = 2; This returns the second highest (dr_desc = 2) and second lowest (dr_asc = 2). Alternatively, use subqueries: SELECT MAX(value) FROM table WHERE value < (SELECT MAX(value) FROM table) for second highest, and SELECT MIN(value) FROM table WHERE value > (SELECT MIN(value) FROM table) for second lowest. Both approaches run in O(n) time and use a single scan of the table.

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 — invisible to screen sharing.

Get Assisting AI — Starts at ₹500