Skip to main content
DevHivesBlog

Search the blog

Find a post by title, tag or topic

Second Highest Salary in SQL: 5 Methods That Handle Ties Correctly

The safest way to find the second highest salary in SQL is a MAX subquery that skips tied top values. Five methods work across MySQL and SQL Server, but only some return NULL when no second value exists.

Arnab Biswas8 min read
WhatsApp
A SQL result table with one row highlighted, showing the second highest salary query result

Say you are taking an online SQL test for your first job. The question asks for the second highest salary in the employees table. You sort salaries from high to low, skip one row and submit. The sample test passes.

Then the hidden test fails. Its data had two people tied for the top salary, and your query read "second highest" one way while the checker read it another way. Same question, four lines of SQL, and the result depends on what the word "distinct" means here.

The safest way to find the second highest salary in SQL is a MAX subquery: select the largest salary that is smaller than the overall maximum. It skips tied top salaries and returns NULL when no second value exists. The plain OFFSET query is wrong on ties unless you add DISTINCT, and OFFSET and DENSE_RANK return no row, not NULL, when no second value exists; the scalar wrapper is a fix for OFFSET, not a separate idea. Use DENSE_RANK when you need the Nth highest or the employee names.

Decide what second highest means before you write SQL

Take a table where two people earn 9000 and one earns 7000: "second highest" can mean 9000 (the second row) or 7000 (the second distinct value). Interviewers almost always want 7000, and the Prepshotz walkthrough of this question builds its whole sample table around that trap.

Every query further down the page runs against the Prepshotz sample data from that walkthrough. Ava and Liam share the top salary, Noah and Zoe share the next one, and Mia earns the least.

CREATE TABLE employees (
  name   VARCHAR(50),
  salary INT
);
INSERT INTO employees (name, salary) VALUES
  ('Ava', 9000), ('Liam', 9000),
  ('Noah', 7000), ('Zoe', 7000),
  ('Mia', 6500);

DataLemur's version of the problem, tagged as a FAANG interview question, adds one more condition: display the salary only once, even when several people earn it. This problem often appears next to other SQL rounds. My list of data analyst interview questions covers the topics that come up alongside it.

Watch: Find Nth Highest Salary in SQL | 5 Different Ways | Most Important SQL Interview Question — CodeEra (YouTube)

Use a MAX subquery for the simple case

Find the highest salary. Then return the highest salary that is smaller than it. Ties at the top cannot interfere, which is why SQLMentor lists this method first.

SELECT MAX(salary) AS second_highest
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);

This runs unchanged in MySQL and SQL Server. The inner query finds the top value. The outer query keeps Noah and Zoe at 7000 plus Mia, then picks the largest of their salaries.

Delete everyone except Ava and Liam and run it again. The WHERE clause now matches zero rows, and MAX over zero rows returns NULL, as the SQLMentor article notes. That NULL is the behaviour interviewers like: it says "there is no second value" without an error or an empty grid.

Write this one first in an interview. You can explain every line out loud in under a minute, and Prepshotz gives the same advice: start here, then reach for DENSE_RANK when the interviewer asks for names or a different N.

Skip rows with OFFSET and FETCH or LIMIT

Sort descending and skip one row: MySQL uses LIMIT 1 OFFSET 1, SQL Server uses OFFSET 1 ROWS FETCH NEXT 1 ROWS ONLY. Both return 9000 when two people tie for the top unless you add DISTINCT, as Prepshotz shows on its sample data.

The reason is simple. After sorting, row one is Ava and row two is Liam, and they earn the same amount. Skipping one row lands you on another copy of the top salary.

-- MySQL: wrong on tied data
SELECT salary FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET 1;
-- MySQL: fixed with DISTINCT
SELECT DISTINCT salary FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET 1;
-- SQL Server: wrong on tied data
SELECT salary FROM employees
ORDER BY salary DESC
OFFSET 1 ROWS FETCH NEXT 1 ROWS ONLY;
-- SQL Server: fixed with DISTINCT
SELECT DISTINCT salary FROM employees
ORDER BY salary DESC
OFFSET 1 ROWS FETCH NEXT 1 ROWS ONLY;

SQL Server only accepts OFFSET and FETCH after an ORDER BY clause, so a query that leaves ORDER BY out raises a syntax error instead of returning rows.

Wrap the query in a scalar subquery to return NULL

Putting the OFFSET query inside SELECT (...) turns an empty result into one row containing NULL, which is what LeetCode-style checkers expect, according to the Prepshotz guide.

-- MySQL
SELECT (
  SELECT DISTINCT salary FROM employees
  ORDER BY salary DESC
  LIMIT 1 OFFSET 1
) AS second_highest;
-- SQL Server
SELECT (
  SELECT DISTINCT salary FROM employees
  ORDER BY salary DESC
  OFFSET 1 ROWS FETCH NEXT 1 ROWS ONLY
) AS second_highest;

The outer SELECT has no FROM clause, so it always produces exactly one row. When the inner query finds nothing, that row holds NULL.

Rank with DENSE_RANK to get any Nth salary

DENSE_RANK numbers distinct salaries 1, 2, 3 without gaps, so filtering rank = N returns every employee at that salary and works for any N, as SQLMentor explains.

WITH ranked AS (
  SELECT name, salary,
         DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk
  FROM employees
  WHERE salary IS NOT NULL
)
SELECT name, salary
FROM ranked
WHERE rnk = 2;

On the sample table this returns two rows, Noah and Zoe, matching the Prepshotz result. That is the answer to give when the interviewer asks "who earns the second highest salary?" instead of "what is it?"

Do not swap in RANK. RANK skips numbers after a tie, giving 1, 2, 2, 4, while DENSE_RANK gives 1, 2, 2, 3, per SQLMentor. When Ava and Liam both get rank 1, RANK jumps straight to 3 for Noah, and WHERE rnk = 2 returns nothing.

For the Nth highest, change the number in the last line. In SQL Server you can make it a variable:

-- SQL Server: variable and CTE together
DECLARE @n INT = 3;
WITH ranked AS (
  SELECT name, salary,
         DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk
  FROM employees
  WHERE salary IS NOT NULL
)
SELECT name, salary FROM ranked WHERE rnk = @n;
-- MySQL: write the number directly, for example WHERE rnk = 3

Count higher salaries with a correlated subquery

Count, for each row, how many distinct salaries are higher; the row whose count equals 1 holds the second highest, with no window function needed, a method SQLMentor includes for older databases.

SELECT DISTINCT e1.salary AS second_highest
FROM employees e1
WHERE 1 = (
  SELECT COUNT(DISTINCT e2.salary)
  FROM employees e2
  WHERE e2.salary > e1.salary
);

Take Noah's row. Only one distinct salary sits above his, so his count is one and his salary is returned. For the Nth highest, replace the 1 with N minus one.

Pros

  • Runs on old MySQL and SQL Server versions that lack window functions.
  • Easy to explain: "count the salaries above me."

Cons

  • Slow on big tables, because the inner query runs once for every row.
  • Returns no row, not NULL, when there is no second value.

Five methods compared across MySQL and SQL Server

No method wins every case: pick the MAX subquery for the quick answer, DENSE_RANK for the Nth value or names, and the scalar wrapper when a checker wants NULL. The table below is built from the SQLMentor and Prepshotz pages.

MethodMySQL syntaxSQL Server syntaxTiesOne distinct salaryNULLsUse it when
MAX subqueryMAX(salary) WHERE salary < (SELECT MAX(salary) ...)Same as MySQLYesReturns NULLIgnored by MAXYour first answer
OFFSET / LIMIT with DISTINCTLIMIT 1 OFFSET 1OFFSET 1 ROWS FETCH NEXT 1 ROWS ONLYOnly with DISTINCTNo rowFilter them outThe interviewer asks for a sort-based answer
Scalar-wrapped OFFSETSELECT (... LIMIT 1 OFFSET 1)SELECT (... OFFSET 1 ROWS FETCH NEXT 1 ROWS ONLY)Only with DISTINCTReturns NULLFilter them outA checker expects one row with NULL
DENSE_RANKDENSE_RANK() OVER (ORDER BY salary DESC)Same as MySQLYesNo rowFilter them outYou need names or any N
Correlated subqueryWHERE 1 = (SELECT COUNT(DISTINCT ...))Same as MySQLYesNo rowNULL rows are skippedNo window functions available

Check which dialect the test platform runs before you type. Company tests in India and the US use both MySQL and SQL Server, and the OFFSET row is the one where the syntax differs. If you want to know how much these SQL rounds count in hiring, I looked at fresher data analyst hiring in real numbers.

Common mistakes with ties, single salaries and NULLs

Three inputs separate a pass from a fail: duplicate top salaries, a table with only one distinct salary, and NULL salary rows that sort first in some databases. DataLemur's checker tests the duplicate case directly by asking for each salary only once.

Run any answer through this checklist before you submit:

  1. Duplicate the top salary

    Give two people the highest pay. The result must be the next distinct value, not the top one again.

  2. Keep one distinct salary

    Make every salary the same. Decide whether the checker wants NULL or an empty result, and pick the method that gives it.

  3. Empty the table

    Remove every row, or set every salary to NULL. The query should still run without an error.

  4. Mix in a NULL

    Add one employee with a NULL salary. The answer must not change.

  5. Compare with the MAX subquery

    Run the MAX version on the same data. If the two results differ, find out why before you submit.

For the NULL case, add WHERE salary IS NOT NULL to any sort-based or ranking query. Prepshotz points out that PostgreSQL puts NULLs first when sorting in descending order, so an unfiltered query can return NULL as the "highest" salary.

Your next step: create the five-row sample table from the first section in MySQL or SQL Server, and run all five queries against it. Then open the DataLemur second-highest-salary problem and solve it without looking at your notes.

ShareWhatsAppLinkedInX

Picked from the tags and topic of this post.

A checkmark and a cross, representing the correct and wrong answers for SQL commands.
technology8 min read

DELETE, TRUNCATE, and DROP in SQL: The Difference Interviewers Test

DELETE removes chosen rows, TRUNCATE empties the table but keeps its structure, and DROP removes the table itself. But the rollback answer changes with the database, and a confident yes or no will be wrong for at least one popular database.

Arnab Biswas
An AI sparkle beside a struck-through copy icon, showing the post is about using AI as a study tutor, not a shortcut.
technology9 min read

Best AI for Students to Study in 2026: Free Tools That Work in India

ChatGPT's free plan with Study mode and Gemini's free tier cover notes, flashcards, and practice questions for most Indian students. Google's free year of AI Pro is for US college students only, so this guide matches each free tool to one exam phase.

Arnab Biswas