How would you find the Nth highest salary in a table

Published: 30 April 2024
on channel: Senior Classroom
64
8

How would you find the Nth highest salary in a table?

You can use a subquery with the DISTINCT keyword and ORDER BY clause. For example:

SELECT DISTINCT Salary FROM Employees ORDER BY Salary DESC LIMIT N-1, 1;

Let's break it down:

SELECT DISTINCT Salary: This selects all distinct salary values from the Employees table.

ORDER BY Salary DESC: This orders the salary values in descending order, so the highest salary comes first.

LIMIT N-1, 1: This limits the result to the (N-1)th row, starting from 0, and retrieves only one row. This effectively gives you the Nth highest salary.

For example, if you want to find the 3rd highest salary, you would replace N with 3, so it becomes:

SELECT DISTINCT Salary FROM Employees ORDER BY Salary DESC LIMIT 2, 1;

This query will return the 3rd highest salary from the Employees table.


Watch video How would you find the Nth highest salary in a table online without registration, duration hours minute second in high quality. This video was added by user Senior Classroom 30 April 2024, don't forget to share it with your friends and acquaintances, it has been viewed on our site 64 once and liked it 8 people.