×

Nth highest salary

The most common and important question asked in interviews that how we can find the Nth highest salary in a table (2nd highest salary, 3rd highest salary, or Nth highest salary), where N could be 2nd, 3rd, 4th, 5th or anything.

Each programmer knows the easiest way to find the nth highest salary is using SQL (Structured Query Language) in a table.

Whenever the interviewer asks you a question about the 2nd highest salary, 4th highest salary, and so on, to solve this question, we should know about some important concepts like a subquery,  function to be used like row_num(), Rank Rank (), etc.

This article will let you know different ways to find the Nth Highest Salary.

Consider the existing tables which have the following records:

Table: Employees

EMPLOYEEIDFIRST_NAMELAST_NAMESALARYCITYDEPARTMENTMANAGERID
1001VAIBHAVIMISHRA65500PUNEORACLE1
1002VAIBHAVSHARMA60000NOIDAC#5
1003NIKHILVANI50500JAIPURFMW2
2001PRACHISHARMA55500CHANDIGARHORACLE1
2002BHAVESHJAIN65500PUNEFMW2
2003RUCHIKAJAIN50000MUMBAIC#5
3001PRANOTISHENDE55500PUNEJAVA3
3002ANUJAWANRE50500JAIPURFMW2
3003DEEPAMJAUHARI58500MUMBAIJAVA3
4001RAJESHGOUD60500MUMBAITESTING4
4002ASHWINIBAGHAT54500NOIDAJAVA3
4003RUCHIKAAGARWAL60000DELHIORACLE1
5001ARCHITSHARMA55500DELHITESTING4

Nth highest salary using a correlated subquery

A correlated subquery is a special type of subquery, where the subquery depends on the main query and is executed for every row returned by the main query.

Syntax:

SELECT salary from employees e1WHERE N-1 = (SELECT COUNT (DISINCT salary) FROM employees e2 WHERE e2.salary > e1.salary)

Where N can be replaced with numbers 2, 3, or 4.

Example 1: Write a query to find the 4th highest salary:

SELECT employeeid, salary from employees e1WHERE 3 = (SELECT COUNT (DISTINCT salary) FROM employees e2 WHERE e2.salary > e1.salary)

Where N = 4, N -1: 4 -1 = 3.

4th highest salary from the table

Output:

EmployeeidSalary
300358500

Explanation:

The distinct keyword is there to handle the duplicated salaries in the table. To search for the Nth highest salary, we only consider non-duplicates salaries. The highest salary means no salary is higher than it. The second-highest salary means only one salary is greater than it. The third-highest salary means only two salaries are higher than the third salary, similarly Nth highest salary means N-1 salaries are greater than it.

The fourth highest salary is 58500 of employee id 3003.

Example 2: Write a query to find the 3rd highest salary:

SELECT employeeid, salary from employees e1WHERE 3 - 1 = (SELECT COUNT (DISTINCT salary) FROM employees e2 WHERE e2.salary > e1.salary)

Where N = 3, N -1: 3 -1 = 2.

2nd highest salary from the table

Output:

EmployeeidSalary
100260000
400360000

The second highest salary is 58500 of two employee id 1002 and employee id 4003.

Example 3: Write a query to find the 5th highest salary:

SELECT employeeid, salary from employees e1WHERE 6 - 1 = (SELECT COUNT (DISTINCT salary) FROM employees e2 WHERE e2.salary > e1.salary)

Where N = 6, N -1: 6 -1 = 5.

5th highest salary from the table

Output:

EmployeeidSalary
400254500

The fifth highest salary is 54500 of employee id 4002.

Nth Highest salary using LIMIT keyword

Syntax:

SELECT salary FROM employees ORDER BY salary desc LIMIT N-1, 1;

Example 1: Write a query to find 2nd highest salary.

SELECT employeeid, salary FROM employees ORDER BY salary desc LIMIT 1, 1;

Output:

EmployeeidSalary
200265500

Limit 1, 1 in the query says how much the highest salary is to be displayed.

If you write 1, 2 outputs will be like this

EmployeeidSalary
200265500
400160500

Nth Highest salary using TOP keyword

The scenario is to calculate the Nth highest employee salary from the employees' table. The steps are as follows:

1. First step is to search the employees’ TOP unique salary from the table.
2. The next step is to calculate the minimum salary among all the salaries resulting from the first step. By this step, we get Nth highest salary.
3. From the result of the above steps, identify the details of the employee whose salary is the minimum salary.

Example 1:

SELECT * FROM employees WHERE salary = (SELECT MIN(salary) FROM employees WHERE salary IN(SELECT DISTINCT TOP N salary from employees ORDER BY salary DESC ));

The above SQL statement is used to find the details of the employees with the Nth highest salary.

Let’s see the explanation of the above SQL statement in brief:

Consider N = 4.

Whenever any SQL query includes a sub-query, remember the inner query will execute first then the outer query will get executed.

The following result will be generated by the query "SELECT DISTINCT TOP N salary from employees ORDER BY salary DESC," which will generate the following result.

Salary
65500
60500
60000
58500

The next outer query is: "SELECT MIN(salary) FROM employees WHERE salary IN (the output of a previous SQL query.

Salary
58500

From the above result, it is verified that the required fourth-highest salary is 58500.

Lastly, the main query is SELECT * FROM employees WHERE salary = output of previous SQL query. The output of this query will be the result of the employees having the fourth-highest salary.

FIRST_NAMESALARY
DEEPAM58500

Example 2:

SELECT * FROM employees WHERE salary = (SELECT MIN(salary) FROM employees WHERE salary IN(SELECT DISTINCT TOP N salary from employees ORDER BY salary DESC ));

The above SQL statement is used to find the details of the employees with the Nth highest salary.

Let’s see the explanation of the above SQL statement in brief:

Consider N = 5.

Whenever any SQL query includes a sub-query, remember the inner query will execute first then the outer query will get executed.

The following result will be generated by the query "SELECT DISTINCT TOP N salary from employees ORDER BY salary DESC," which will generate the following result.

Salary
65500
60500
60000
58500
55500

The next outer query is: "SELECT MIN(salary) FROM employees WHERE salary IN (the output of a previous SQL query.

Salary
55500

From the above result, it is verified that the required fifth-highest salary is 55500.

Lastly, the main query is SELECT * FROM employees WHERE salary = output of previous SQL query. The output of this query will be the result of the employees having the fifth-highest salary.

FIRST_NAMESALARY
PRACHI55500

Nth Highest salary using Row_Num() function

Example:

SELECT MIN(salary) FROM(SELECT DISTINCT salary FROM employees ORDER  BY salary DESC) WHERE rownum < 3;
  • To calculate the third-highest salary, use rownum < 4
  • To calculate the second-highest salary, use rownum < 3

Output:

MIN(salary
60500

Let's see how the query works:

Step 1: The query includes subquery means inner query and outer query. We all know when the subquery is used in the query, the inner query is first executed

First, the inner query will get executed then the outer queries will be executed based on the output produced by the inner query:

Inner query:    

SELECT MIN(salary) FROM(SELECT DISTINCT salary FROM employees ORDER  BY salary DESC) WHERE rownum < 3;

Output of the inner query:

Salary
65500
60500
60000
58500
55500
54500
50500
50000

As we used a distinct keyword in the query, the duplicate salary will get eliminated. Unique salary will be displayed as the result of the inner query.

Step 2: As the server is done with an inner query, we are executing the outer query of the nested query into the output we obtained from the inner query

SELECT MIN(salary) FROM(SELECT DISTINCT salary FROM employees ORDER  BY salary DESC) WHERE rownum < 3;

SELECT MIN(salary) FROM (inner query output): select minimum salary from the inner query output, which is 50000 and 50000 is not the second-highest salary, because of which we have used rownum < 3, which will give the number of rows from the top which is less than 3 means only 2.

The output of WHERE rownum < 3:

Salary
65500
60500

Step 3: The Last part of the query, which is the SELECT MIN(salary) from (the output  of WHERE rownum<3):

The final output of the query:

Salary
60500

60500 is the second-highest salary on the employees' table.

Nth Highest salary using Rank Rank () function

Example:

SELECT * FROM(SELECT First_Name, salary, dense_rank()      OVER(ORDER BY salary DESC) rank FROM employees) WHERE rank =&num;

- To calculate the third-highest salary, use num =  3

- To calculate the second-highest salary, use num = 2

We will go for num = 2.

The final output:

First_NameSalaryRank
Rajesh605002

Output of the inner query:

SELECT(First_Name, Salary, dense_rank() OVER(ORDER BY salary DESC) Rank FROM employees

The Dense_rank() function calculates the Rank of each row in an order group of rows in ascending order and returns the Rank as a number. The Rank starts from 1 and so on.

In case of two or more than two rows have the same salary, it assigns an equal rank to all the rows.

Output of the inner query:

First_nameSalaryRank
VAIBHAVI655001
BHAVESH655001
RAJESH605002
VAIBHAV600003
RUCHIKA600003
DEEPAM585004
PRACHI555005
PRANOTI555005
ARCHIT555005
ASHWINI545006
NIKHIL505007
ANUJA505007
RUCHIKA500008

In the output, we can see the same ranking to duplicate salary.

Step 2: As the server is done with an inner query, we are executing the outer query of the nested query into the output we obtained from the inner query

SELECT * FROM(SELECT(First_Name, Salary, dense_rank() OVER(ORDER BY salary DESC) rank FROM employees) WHERE rank = &num;

Select * from will select all the rows which are not the second-highest salary because we have used RankRank where num = 2 will give matching rows according to the value entered by the user for num.

As we used num = 2, the output will be

First_nameSalaryRank
RAJESH605002
  • To find the third salary set num = 3,
  • To find the fourth salary set num = 4, and so on.

Related Topics

SQL INSERT Statement

In this tutorial, we will help you to understand and learn how to insert records to the table in SQL with the help of examples. SQL INSERT query is used to...

5 minutes read.

SQL Right Join

The SQL Right Join query displays all the table records and similar records from the left table. The query display zero records if it doesn’t find any similar records. If...

4 minutes read.

SQL COPY Table

In this tutorial, we will learn how to copy tables in SQL with the help of examples. Using the SELECT INTO statement in the SQL we can copy one table into...

4 minutes read.

SQL DROP Database

This tutorial will help us understand how to drop a database from the SQL Server with a few examples. The DROP command removes all the objects stored in the database and...

4 minutes read.

SQL WHERE Statement

SQL WHERE Statement Introduction WHERE clause is used to include a condition while fetching data from tables.When you have to specify a condition that has to be obeyed while data is...

9 minutes read.

How to remove duplicates in SQL

Introduction There are some specific rules that needs to be followed while creating the database objects. To improve the performance of a database, a primary key, clustered and non-clustered indexes, and...

9 minutes read.

SQL Arithmetic Operators

This page contains all the information, learn about SQL Arithmetic Operators concept in the SQL table with the help of examples. The Arithmetic Operators is used to perform mathematical calculations on...

5 minutes read.

SQL Select Distinct

The SQL DISTINCT query is used to fetch unique values from the tables using the SELECT statement in the SQL. There may be a situation that arises when you want to...

4 minutes read.

GROUP BY vs ORDER BY

The GROUP BY clause and ORDER BY clause in SQL are used to arrange data obtained by SQL queries. The important difference between the GROUP BY clause and ORDER BY...

4 minutes read.

SQL Create Database

This tutorial will help us understand how to CREATE a Database in SQL with a few examples. The first step for storing structured records in the database is creating the databases. We...

4 minutes read.

SQL Data Manipulation Language

Data Manipulation Language manipulates/make changes in data present in a table. It only affects data/records of table, not on the schema/structure of table. INSERT, UPDATE, DELETE are the commands of DML. INSERT: Stores...

2 minutes read.

How to Add Comments in SQL?

How to Add Comments in SQL Comments are text notes that are incorporated into the program to make the code easier to understand. In SQL, commenting is used to explain various sections...

2 minutes read.

SQL SELECT WHERE Clause

In this SQL section, we will help you understand the concept of the SQL SELECT WHERE clause with a few examples. The WHERE clause in SELECT query displays those records as...

5 minutes read.

Check Constraint in SQL

The Check Constraint in SQL is the rule or set of rules used to limit the data range that can be entered in a table column. Check constraint is used...

8 minutes read.

How to drop a column in SQL?

How to drop a column in SQL Introduction To delete a column from an already created table, one needs to use the ALTER command along with the DROP COLUMN clause. Syntax: ALTER TABLE tablename...

4 minutes read.

How to use INNER JOIN in SQL

In this article, we will learn about the INNER JOIN concept and how to use it in SQL with the WHERE clause. What is INNER JOIN in SQL? Inner Join is a...

6 minutes read.

SQL SELECT AND Operator

This SQL tutorial explains and helps us understand how to use the AND Operator in the SELECT query with examples. The AND Operator is used to fetch the table’s records if...

2 minutes read.

space() function in SQL

 This function returns a string with a specified number of spaces. If we specify a number, it returns the strings having that specified number of spaces. SPACE Function is available...

2 minutes read.

SQL CASE

This page contains all the information about SQL CASE. The CASE is an If-Else type of logical query used in the statement. The CASE in Structured Query Language is similar...

5 minutes read.

SQL HAVING Clause

In this tutorial, we will understand the HAVING clause concept in SQL with the help of examples. The HAVING Clause in the SQL is used as we cannot use the WHERE...

3 minutes read.