There are several ways to find out Nth highest salary data in SQL query. The most commonly used methods for many is – Using MIN() and MAX() functions. Here in this article we will discuss about the three methods to get it done in SQL. In this article we’ll also discuss 2nd highest salary in sql, sql select nth highest value.
How To Find Nth Highest Salary In Sql
One of the most common SQL interview questions is to find the Nth highest salary of employees, where N could be 2, 3, 4 or anything e.g. find the second highest salary in SQL. Sometimes this question is also twisted as to find the nth minimum salary in SQL. Since many Programmers only know the easy way to solve this problem e.g. by using SQL IN clause, which doesn’t scale well, they struggle to write the SQL query when the Interviewer keeps asking about the 4th highest, 5th highest and so on. In order to solve this problem effectively, you need to know about some key concepts like a correlated subquery, window functions like ROW_NUMER(), RANK(), and DENSE_RANK(), etc. Once you know the generic logic to solve this problem, you can tackle all those variations by yourself.
In this article, I’ll show you 4 ways to solve this problem e.g. by using the correlated subquery, using ROW_NUMBER(), using TOP in SQL SERVER, and using LIMIT keyword in MySQL.
By the way, if you are new to Microsoft SQL Server and T-SQL then I also suggest you join a comprehensive course to learn SQL Server fundamentals and how to work with T-SQL. If you need a recommendation then I suggest you go through the Microsoft SQL for Beginners online course by Brewster Knowlton on Udemy. It”s a great course to start with T-SQL and SQL queries in SQL Server.
Sample table and data for Nth Highest Salary Problem
Before solving this problem we need some sample data to visualize the problem better, let’s create an employee table with some data.
Use below query to create a table and build schema:
-- creating Employee table in Oracle CREATE TABLE Employee (name varchar(10), salary int); -- inserting sample data into Employee table INSERT INTO Employee VALUES ('Rick', 3000); INSERT INTO Employee VALUES ('John', 4000); INSERT INTO Employee VALUES ('Shane', 3000); INSERT INTO Employee VALUES ('Peter', 5000); INSERT INTO Employee VALUES ('Jackob', 7000);
Nth highest salary using a correlated subquery
One of the most common ways to solve this problem of finding the Nth maximum salary from the Employee table is by using the correlated subquery. This is a special type of subquery where the subquery depends upon the main query and execute for every row returned by the main query. It’s slow but it can solve problems which are difficult to solve otherwise. Let’s see the SQL query to find the Nth highest salary using the Correlated subquery.
SQL Query:
SELECT name, salary FROM #Employee e1 WHERE N-1 = (SELECT COUNT(DISTINCT salary) FROM #Employee e2 WHERE e2.salary > e1.salary)
for the 2nd maximum you can replace N with 2, and for 3rd maximum replace N with 3, here is the output:
2nd highest salary:
SELECT name, salary FROM #Employee e1 WHERE N-1 = (SELECT COUNT(DISTINCT salary) FROM #Employee e2 WHERE e2.salary > e1.salary)SELECT name, salary FROM #Employee e1 WHERE 2-1 = (SELECT COUNT(DISTINCT salary) FROM #Employee e2 WHERE e2.salary > e1.salary) Result: name salary Peter 5000
3rd highest salary:
SELECT name, salary FROM #Employee e1 WHERE 3-1 = (SELECT COUNT(DISTINCT salary) FROM #Employee e2 WHERE e2.salary > e1.salary) Result: name salary John 4000
Explanation :
The distinct keyword is there to deal with duplicate salaries in the table. In order to find the Nth highest salary, we are only considering unique salaries. The highest salary means no salary is higher than it, the Second highest means only one salary is higher than it, 3rd highest means two salaries are higher than it, similarly Nth highest salary means N-1 salaries are higher than it.
Pros :
1) The generic solution works in all databases including Oracle, MySQL, SQL SERVER, and PostgreSQL.
Cons :
1) Slow, because the inner query will run for every row processed by the outer query.
The nth highest salary in SQL SERVER using TOP keyword
You can use the TOP keyword to find the Nth highest salary in SQL SERVER. This is also faster than the previous solution because here we are calculating Nth maximum salary without a subquery.
SELECT TOP 1 salary FROM ( SELECT DISTINCT TOP N salary FROM #Employee ORDER BY salary DESC ) AS temp ORDER BY salary
Explanation:
By default ORDER BY clause print rows in ascending order, since we need the highest salary at the top, we have used ORDER BY DESC, which will display salaries in descending order. Again DISTINCT is used to remove duplicates. The outer query will then pick the topmost salary, which would be your Nth highest salary.
And, if you like books and just learning these queries from the interview’s sake then I suggest you first read a good book on SQL like Head First SQL. It will help you to build your fundamentals.
3rd highest salary in SQL SERVER
SELECT TOP 1 salary FROM ( SELECT DISTINCT TOP 3 salary FROM #Employee ORDER BY salary DESC ) AS temp ORDER BY salary Result: salary 4000
Here is another example where we have used the TOP keyword to find the second highest salary in Microsoft SQL SERVER 2008.
Nth maximum salary in MySQL using LIMIT keyword
Similar to TOP, MySQL also supports a LIMIT keyword, which provides pagination capability. You can find the nth highest salary in MySQL without using subquery as shown below:
SELECT salary FROM Employee ORDER BY salary DESC LIMIT N-1, 1
2nd highest salary in MySQL without subquery:
SELECT salary FROM Employee ORDER BY salary DESC LIMIT 1,1 salary 5000
3rd highest salary in MySQL using LIMIT clause:
SELECT salary FROM Employee ORDER BY salary DESC LIMIT 2,1 salary 4000
Nth highest salary in MySQL using LIMIT clause:
SELECT salary FROM Employee ORDER BY Salary DESC LIMIT n-1,1
Explanation :
The benefit of this approach is that it’s faster than a correlated query approach but its vendor dependent. This solution will only work in a MySQL database.
Nth highest salary in Oracle using ROW_NUMBER() function
SELECT * FROM ( SELECT e.*, ROW_NUMBER() OVER (ORDER BY salary DESC) rn FROM Employee e ) WHERE rn = N; /*N is the nth highest salary*/
Here is the 2nd highest salary in Oracle using ROW_NUMBER() window function:
SELECT * FROM ( SELECT e.*, ROW_NUMBER() OVER (ORDER BY salary DESC) rn FROM Employee e ) WHERE rn = 2; Output NAME SALARY RN Peter 5000 2
and here is 3rd highest salary in Oracle:
SELECT * FROM ( SELECT e.*, ROW_NUMBER() OVER (ORDER BY salary DESC) rn FROM Employee e ) WHERE rn = 3;
By the above code has a problem. It is not handling duplicate salaries properly. For example, in our table we have two employees with salary 3000, that’s our 4th highest salary, but above code will print the same salary, albeit different employee for both 4th and 5th maximum as shown below:
SELECT * FROM ( SELECT e.*, ROW_NUMBER() OVER (ORDER BY salary DESC) rn FROM Employee e ) WHERE rn = 5; Result: NAME SALARY RN Shane 3000 5
In oracle, you can also use SQL statements to build schema and run sample SQL.
You can also do the same thing by using the RANK() window function in Oracle, but that’s for another day. This is more than enough to answer the SQL interview question, the print nth highest salary of an employee in the Oracle.
That’s all about how to find the nth highest salary in SQL. The easiest way to find nth maximum/minimum salary is by using the correlated subquery, but it’s not the fastest way. Better ways are database dependent e.g. you cause TOP keyword in SQL SERVER, LIMIT keyword in MySQL, and ROW_NUMBER() window function in Oracle to calculate the nth highest salary. The normal subquery way is good for the second maximum but after that, it becomes really nested and cluttered.
2nd highest salary in sql
We will execute the above problem in 3 steps to find the second highest salary in SQL, that are:
- Creating a table
- Inserting values in table
- Writing query to find second highest salary
Now, let’s look at each of the above steps in detail.
Creating Table
The first step is to create a table. Here, we’ll create a table named as Employee having attributes ID, NAME and SALARY.
SQL query for creating the schema for our table is given below.
CREATE TABLE Employee
(
ID INTEGER,
NAME VARCHAR(20),
SALARY INTEGER
)
Output
Now that we have the schema for the table, let’s move on to the next step where we will insert some values in the schema to get the desired end result.
Inserting Values in Table
In this step, we will insert some sample records into the table.
INSERT INTO Employee VALUES(1,’Mandy’,12000);
INSERT INTO Employee VALUES(2,’Chris’,15000);
INSERT INTO Employee VALUES(3,’Henry’,10000);
INSERT INTO Employee VALUES(4,’Katy’,10000);
INSERT INTO Employee values(5,’Adams’,11000);
The above query will give you the table as follows:
Webinar: An Overview of Job Guarantee Programs
Get Job-Ready With Our Intense BootcampsREGISTER NOW
Writing Query to Find Second Highest Salary in SQL
To find the second highest salary in the above table, we will use the concept of subquery, which means that firstly, we will find the highest salary in the table and then we will nest that query to a subquery to find the second highest salary in SQL.
To find the highest salary in the table, write the following query.
SELECT MAX(SALARY) FROM Employee;
This will give you the output as 15000, i.e the highest salary in the table above.
Output-
Now, to find the second highest salary, we nest the above query into another query as written below.
SELECT MAX(SALARY) FROM Employee WHERE SALARY < (SELECT MAX(SALARY) FROM Employee);
This query will give you the desired output i.e 12000, which is the second highest salary.
Output-
sql select nth highest value
Problem Statement : Write an SQL query to find the nth largest value from the column using LIMIT and OFFSET.
Example-1 :
Table – BILLS
FLATNo. | ElectricityBill |
---|---|
101 | 1000 |
102 | 1500 |
103 | 1300 |
201 | 2300 |
202 | 6700 |
203 | 7500 |
204 | 1300 |
301 | 2300 |
The above table has the electricity bills of all the flats in an apartment. You have to find the nth largest electricity bill in the table.
SELECT DISTINCT ElectricityBill AS NthHighestElectricityBill FROM Bills ORDER BY ElectricityBill DESC LIMIT 1 OFFSET n-1;
Here n should be an integer whose value must be greater than zero.
Explaination :
In the above query, we are sorting the values of ElectricityBill column in descending order using Order By clause and by selecting only distinct values. After sorting it in descending order we have to find the Nth value from the top, so we use OFFSET n-1 which eliminates the top n-1 values from the list, now from the remaining list we have to select only its top element, to do that we use LIMIT 1.
If we want to find the 3rd highest electricity bill the query will be –
SELECT DISTINCT ElectricityBill AS 3rdHighestElectricityBill FROM Bills ORDER BY ElectricityBill DESC LIMIT 1 OFFSET 2;
The result of the above query will be –
3rdHighestElectricityBill |
---|
2300 |
Example-2 :
Table – EmployeeSalary
EmployeeID | SalaryInThousands |
---|---|
1A234 | 450 |
1D765 | 259 |
5A567 | 320 |
3B653 | 450 |
3A980 | 259 |
9R345 | 128 |
2A748 | 316 |
The above table has the salaries of employees working in a small company. Find the employee id who is earning the 4th highest salary.
SELECT EmployeeID AS 4thHighestEarningEmployee FROM EmployeeSalary ORDER BY SalaryInThousands DESC LIMIT 1 OFFSET 3;
Explaination :
Here distinct is not used because we need employee whose earnings stand at 4th place among all the employee’s (i.e 316k not 259k).
The result of the above query will be –
4thHighestEarningEmployee |
---|
2A748 |