CodeEraFree roadmap

Blogs

Find Nth Highest Salary in 5 Different Ways

Interview question  , 2 min read

"Find the Nth highest salary" is one of the most common SQL interview questions. Here are five ways to answer it on an employee table. In each query, replace n with the rank you want, for example 3 for the third highest.

One detail interviewers love: if two people earn the same salary, should they count as one rank or two? The queries below count equal salaries once, which is what "Nth highest salary" normally means.

Method 1: LIMIT and OFFSET (MySQL, PostgreSQL)

SELECT DISTINCT salary
FROM employee
ORDER BY salary DESC
LIMIT 1 OFFSET 2;   -- OFFSET = n - 1, so this is the 3rd highest

We sort salaries from high to low, skip the first n - 1 rows with OFFSET, and take the next one. DISTINCT makes sure that duplicate salaries are not counted twice. In MySQL, write the number directly (or use a variable inside a stored procedure), because OFFSET does not accept an expression like n-1.

Method 2: A correlated subquery

SELECT DISTINCT salary
FROM employee emp1
WHERE n - 1 = (
  SELECT COUNT(DISTINCT salary)
  FROM employee emp2
  WHERE emp2.salary > emp1.salary
);

For each salary in the outer query, the subquery counts how many distinct salaries are higher. The Nth highest salary has exactly n - 1 higher distinct salaries. This works on every database, but it can be slow on large tables.

Method 3: TOP inside a subquery (SQL Server)

SELECT TOP 1 salary
FROM (
  SELECT DISTINCT TOP 3 salary   -- replace 3 with n
  FROM employee
  ORDER BY salary DESC
) AS emp
ORDER BY salary ASC;

The inner query takes the top n distinct salaries in descending order. The outer query sorts those ascending and keeps the first one, which is the Nth highest.

Method 4: DENSE_RANK()

SELECT DISTINCT salary
FROM (
  SELECT salary,
         DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk
  FROM employee
) AS ranked
WHERE rnk = n;

DENSE_RANK gives equal salaries the same rank and does not skip numbers, so rank 3 means the third highest distinct salary. Many people reach for ROW_NUMBER here, but it gives duplicates different numbers, so it returns the wrong answer when salaries repeat.

Method 5: A self join

SELECT emp1.salary
FROM employee emp1
LEFT JOIN employee emp2
  ON emp1.salary < emp2.salary
GROUP BY emp1.salary
HAVING COUNT(DISTINCT emp2.salary) = n - 1;

We join the table to itself so that each salary is paired with every higher salary. After grouping, COUNT(DISTINCT emp2.salary) is the number of higher distinct salaries. We keep the salary where that number is n - 1.

Which one should you use? In an interview, start with DENSE_RANK or LIMIT/OFFSET, since they are the easiest to explain, and mention the correlated subquery as the answer that works everywhere. Practice more in the SQL practice sets.