How to select 3rd highest salary in sql

Find out more about sql salary, sql jobs, 3rd highest salary in sql, how to select 3rd highest salary in sql, data warehousing salary on careerkeg.com

The SQL is used to find the third highest salary in a employee table. First we will create a table and insert some records in it. After that we’ll select the 3rd highest salary from a table using SQL.

SELECT TOP 3 salary FROM employees ORDER BY salary DESC OFFSET 2 ROWS FETCH NEXT 6 ROWS ONLY

The above command is used to select the third highest salary from employees table. This can be achieved by using offset clause. The syntax of this query is as follows:

SELECT TOP 3 salary FROM employees ORDER BY salary DESC OFFSET 2 ROWS FETCH NEXT 6 ROWS ONLY

How to select 3rd highest salary in sql

Introduction

The query first selects the distinct salary values and orders them in descending mode. Then, it selects the top 3 values from the above result and lists them in descending order again to get third highest salary.

SELECT DISTINCT(Salary) FROM Employee

From the results, you can see that Joe is the third highest employee in terms of salary. It shows that he earns more than $25000 per year and has been working for more than 10 years. The query returns four rows out of 6 because there are three employees with a salary greater than $25000 but less than $30500 and one employee who earns a salary greater than $30500.

ORDER BY Salary DESC

The following query returns the third-highest salary:

SELECT DISTINCT(Salary) FROM Employee

ORDER BY Salary DESC

LIMIT 2, 1;

LIMIT 2, 1;

The LIMIT 2,1; query will start at the second record and return only one record. The above query will only work if there are no ties in the data.

select 3rd highest salary in sql

The following examples show how to select 3rd highest salary in sql.

Using a subquery

A subquery is a query that is nested inside another query. The following example returns the number of employees in each department and their highest salary:

SELECT deptno, COUNT(ename) emps ,MAX(sal) highest_sal FROM emp GROUP BY deptno ORDER BY 2 DESC;

Using a correlated subquery

Conclusion

In summary, you can use the following SQL query to select the third highest salary of all employees.

Leave a Reply