2nd-3rd-4th-nth highest salary

3 Best Ways for 2nd 3rd 4th ...nth Highest Salary - [SQL Server]

Method 1 :-
SQL Server 2nd, 3rd, 4th... Highest salary using SUB QUERY!

We can find the 2nd, 3rd, 4th ... nth highest salary using SQL Server the below query, In the below query use top 1 for the 2nd highest salary, top 2 for the 3rd highest salary, top 3 for the 4th highest salary,.... nth for the (n+1) highest salary.

Method 2:-
You can use LIMIT to get 2nd, 3rd, 4th ... nth highest salary!

The examples using SUB QUERY,
--QUERY FOR THE 2ND HIGHEST SALARY
SELECT MAX(salary) AS [2ndHighestSalary]
      FROM Employee  WHERE salary not in (SELECT TOP 1 salary  FROM Employee
 GROUP BY salary ORDER BY salary DESC)

--QUERY FOR THE 3RD HIGHEST SALARY 
SELECT MAX(salary) AS [3rdHighestSalary]
      FROM Employee  WHERE salary  not in (SELECT TOP 2 salary  FROM Employee
GROUP BY salary ORDER BY salary DESC)

--QUERY FOR THE 4TH HIGHEST SALARY 
SELECT MAX(salary) AS [4thHighestSalary]
      FROM Employee  WHERE salary   not in (SELECT TOP 3 salary  FROM Employee
GROUP BY salary ORDER BY salary DESC)

--QUERY FOR THE 5TH HIGHEST SALARY 
SELECT MAX(salary) AS [5thHighestSalary]
      FROM Employee  WHERE salary   not in (SELECT TOP 4 salary  FROM Employee
GROUP BY salary ORDER BY salary DESC)

--QUERY FOR THE NTH HIGHEST SALARY 
SELECT MAX(salary) AS [nthHighestSalary]
      FROM Employee  WHERE salary   not in (SELECT TOP (n-1) salary  FROM Employee
GROUP BY salary ORDER BY salary DESC)


In MySQL simple and sweeter 2nd, 3rd, 4th... Highest salary.
You can use LIMIT to get highest salary!

Examples using MySQL LIMIT,
--QUERY FOR THE 2ND HIGHEST SALARY USINGH LIMIT
SELECT salary FROM Employee ORDER BY salary DESC LIMIT 1, 1;

--QUERY FOR THE 3rd HIGHEST SALARY USINGH LIMIT
SELECT salary FROM Employee ORDER BY salary DESC LIMIT 2, 1;

--QUERY FOR THE 4th HIGHEST SALARY USINGH LIMIT
SELECT salary FROM Employee ORDER BY salary DESC LIMIT 3, 1;

I hope you are enjoying with this post! Please share with you friends. Thank you!

ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..

My Tech Blog - https://www.code-sample.com/
My Books - Book 1 and Book 2

www.code-sample.com/. Powered by Blogger.
^