Skip to main content

From an employees table with name, department and salary, return the second highest salary in each department. For example, if engineering has salaries 100, 100, 90 and 80, the answer for engineering is 90.

Coding rounds · Intermediate 1

Short answer

Rank salaries inside each department with DENSE_RANK() OVER (PARTITION BY department ORDER BY salary DESC) in a CTE, then filter WHERE rnk = 2. DENSE_RANK gives tied salaries the same rank with no gaps, so two people on the top salary do not hide the second value. The cost is a sort per department, O(n log n).

Deeper answer

First clarify the question. Ask whether second highest means the second distinct salary or the second person. Ask what to return for a department with only one distinct salary: no row, or a row with NULL. Ask whether salary can be NULL.

Write a CTE: WITH ranked AS (SELECT department, name, salary, DENSE_RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS rnk FROM employees), and then SELECT department, name, salary FROM ranked WHERE rnk = 2. The filter must sit outside the CTE because a window function cannot be used in WHERE at the same level. Explain the three ranking functions on 100, 100, 90: ROW_NUMBER gives 1, 2, 3, so rank 2 is 100 again; RANK gives 1, 1, 3, so there is no rank 2; DENSE_RANK gives 1, 1, 2, which is what we need.

A department with one distinct salary returns no row. To show it with NULL, left join the list of departments to the result. Test ties at the top, ties at second place, which return several rows, and a one-person department.

What a strong answer covers

Answer it out loud in the mock interview about 2.5 min

Follow-ups to expect

Common mistakes

Learn it

SQL for engineers

Practice Coding rounds questions

More on this topic

Today's AI turns are used

Lessons, roadmaps, videos, practice cards and the code playground stay free with your account, with no limit.