SQL PRACTICE: SQL SERVER - Third Highest Salary

 Q9. How to find the third highest salary from the table below using SQL?

N.B: I am using the following:

Database -> MSSQL

SQL Dialect -> T-SQL


Consider below an employment table as a source data.

Table 1. Employment Table



Ans:
select top 1 salary from (
select top 3 salary
from employment
order by salary desc) as TopThree
order by salary asc;

Table 2. 3rd Highest Salary




Explanation: To find the third highest salary from the provided  table, first I need to find the first three rows with highest salary ordered in descending order. Look at the the query and result below.

select top 3 salary
from employment
order by salary desc;
Table 3. First 3 highest salaries

Now, we have the 3rd highest salary on the last row. In order to have the 3rd highest salary as an output, we have to order the above query (name as alias TopThree) in ascending order and select the first row using Top 1. 

Comments

Popular posts from this blog

SQL PRACTICE: SQL SERVER - DATEADD Function

SQL PRACTICE: SQL SERVER - Unique Records

SQL PRACTICE: SQL SERVER: DATEDIFF Function