As asked
Without writing it on a whiteboard, walk me through how you would structure a SQL query to return the second highest salary within each department from an employees table.
Sample answer outline
Explain a window function approach: DENSE_RANK or ROW_NUMBER partitioned by department and ordered by salary descending, then filter to rank equal to two in an outer query. Cover why DENSE_RANK handles ties differently from ROW_NUMBER, and what happens when a department has only one salary. Mention that a correlated subquery is the older alternative but reads worse and scales poorly.
Expect these follow-ups
- How does your answer change if two people tie for the top salary?
- Why pick DENSE_RANK over ROW_NUMBER here?
- What if the department has fewer than two employees?