Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. Data Science
  3. Question
Data Science

How can I write an SQL query to find 3rd highest salary in a Employees table?

Asked by Celina Lagunas Jun 7, 2024 4.8K views 3 answers
Share

About this question

I am a database analyst at a particular company that maintains an employee database. This particular database includes a table which is called “Employees” which has EmployeeID, Name, Department, and Salary file. Now the management has requested me to find the third Highest salary in the company. How can I write an SQL query to approach this particular task?

Your answer

3 Answers

Ranjana Admin JanBask Expert Latest answer

Answered on Feb 4, 2025

To find the 3rd highest salary in an Employees table using SQL, there are multiple approaches. Here are some of the most commonly used methods:

1. Using LIMIT and OFFSET (for MySQL, PostgreSQL)

This is the simplest method:

SELECT DISTINCT salary 
FROM Employees 
ORDER BY salary DESC 
LIMIT 1 OFFSET 2;

  • ORDER BY salary DESC sorts salaries in descending order.
  • LIMIT 1 OFFSET 2 skips the first two highest salaries and fetches only the third.

2. Using DISTINCT and ORDER BY with LIMIT

Another approach without OFFSET:

SELECT DISTINCT salary 
FROM Employees 
ORDER BY salary DESC 
LIMIT 3;

This returns the top 3 salaries, so you need to take the last row.

3. Using a Subquery (Works in Most SQL Databases)

SELECT MAX(salary) 
FROM Employees 
WHERE salary < (SELECT MAX(salary) FROM Employees 
                WHERE salary < (SELECT MAX(salary) FROM Employees));

  • The innermost query finds the highest salary.
  • The second query finds the second highest.
  • The outermost query gets the third highest.

4. Using DENSE_RANK() (For SQL Server, PostgreSQL, Oracle)

SELECT salary 
FROM (
    SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk 
    FROM Employees
) ranked
WHERE rnk = 3;

  • DENSE_RANK() assigns a unique rank to each distinct salary.
  • We filter for rnk = 3 to get the third highest.

Each method has its advantages depending on the database system. If your table has duplicate salaries, DENSE_RANK() is a reliable choice.

Let me know if you need further clarifications!

Was this helpful?

Fernandobattle

Answered on Nov 19, 2024

@Tomb of the Mask, Thanks for your reply. This is exactly what I was looking for.

Was this helpful?

More Data Science discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest Data Science Blogs

Guides, tips and career advice on Data Science from JanBask experts.