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, duration hours minute second in high quality that is uploaded to the channel Senior Classroom 30 April 2024. Share the link to the video on social media so that your subscribers and friends will also watch this video. This video clip has been viewed 64 times and liked it 8 visitors.