
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Second Highest Salary in SQL
In real-world scenarios, you'll often need to query for the nth highest salary. Let's see how to find the second-highest salary in SQL.
Example
Consider a sample table named Company with columns Employee and Salary:
Table Name: Company
Employee |
Salary |
Adithya | 1000 |
Abhishek | 2500 |
Nandini | 1500 |
Raju | 3000 |
Vikas | 800 |
Method 1: Using a Subquery
In this method, the inner subquery finds the highest salary from the Employee table. The outer query then finds the highest salary by excluding the actual highest salary from the table.
Example
SELECT MAX(Salary) FROM Employee WHERE Salary NOT IN (SELECT MAX(Salary) FROM Employee);
Method 2: Using the LIMIT Clause
Here, the query selects all distinct salary values from the Employee table, orders them in descending order, and then selects the second record using the LIMIT clause.
Example
SELECT DISTINCT Salary FROM Employee ORDER BY Salary DESC LIMIT 1,1;
Note: This method uses the LIMIT keyword, which may not be supported by all database systems. Currently, it's supported in MySQL and PostgreSQL.
Method 3: Using NOT EXISTS
In the outer query, we select the salary from the employees table and alias it as e1.
The inner query also uses the employees table and aliases it as e2. This query checks if there exists a salary in the employees table that is greater than the current salary in the outer query. The NOT EXISTS clause checks if the inner query returns any rows. If the inner query returns no rows, it means there is no salary greater than the current salary in the outer query. In this case, the current salary is the second-highest salary.
Example
SELECT Salary FROM Employee e1 WHERE NOT EXISTS (SELECT 1 FROM Employee e2 WHERE e2.salary > e1.salary);
Method 4: Using the Window Function
Here, a rank will be assigned to each salary in descending order. The second-highest salary will have a rank of 2.
Example
SELECT Salary FROM (SELECT Salary, DENSE_RANK() OVER (ORDER BY Salary DESC) AS rk FROM Employee) AS RE WHERE rk = 2;