Sunday, June 8, 2025

SQL - How to get the 2nd or 3rd max salary from an employee table using sql query?

How to get the 2nd or 3rd max salary from an employee table using sql query?Answer:

Using limit and offset

2nd Maximum Salary

SELECT salary

FROM employee

ORDER BY salary DESC

LIMIT 1 OFFSET 1;

3rd Maximum Salary

SELECT salary

FROM employee

ORDER BY salary DESC

LIMIT 1 OFFSET 2;

Method 1: Using Subqueries

2nd Maximum Salary

SELECT MAX(salary) AS SecondHighestSalary

FROM employee

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

3rd Maximum Salary

SELECT MAX(salary) AS ThirdHighestSalary

FROM employee

WHERE salary < (SELECT MAX(salary) 

                FROM employee 

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

No comments:

Post a Comment

Featured Post

OIC - OIC Utility to Reprocess Failed Real-Time Integration JSON Payloads

📌 Use Case In real-time OIC integrations, JSON payloads are exchanged with external systems via REST APIs. When such integrations fail (du...