top of page
Writer's pictureThe Tech Platform

Write a SQL query to get the nth highest salary from the Employee table.

Updated: Mar 24, 2023

Create Employee Table-

If you want to test in your local database then you can use the following SQL query to create an Employee table and populate it with some sample data. After that, you can run the SQL query to find the Nth highest salary for testing.

CREATE TABLE Employees (     
Id INTTEGER NOT NULL,     
Name VARCHAR(50) PRIMARY KEY       
Salary INTEGER,
Country VARCHAR(50)
);

INSERT the values in the Employees table.

INSERT INTO Employees (ID, Name, Salary, Country) VALUES (12010, 'Anna', $1200, 'Canada');   

INSERT INTO Employees (ID, Name, Salary, Country) VALUES (12000, 'Jason', $935, 'USA');

INSERT INTO Employees (ID, Name, Salary, Country) VALUES (12020, 'Michael', $1050, 'UK');   

INSERT INTO Employees (ID, Name, Salary, Country) VALUES (12030, 'John', $1000, 'Singapore');   

INSERT INTO Employees (ID, Name, Salary, Country) VALUES (12034, 'Jared', $1500, 'America');

INSERT INTO Employees (ID, Name, Salary, Country) VALUES (12022, 'Robert', $2000, 'Canada');   

INSERT INTO Employees (ID, Name, Salary, Country) VALUES (12122, 'David', $2050, 'USA');   

INSERT INTO Employees (ID, Name, Salary, Country) VALUES (12109, 'Betty', $1209, 'USA');

Here we have Employee Table below:


Find the nth Highest Salary-

The nth highest salary where n = 2 is 200. If there is no nth highest salary, then the query should return null.


Syntax:

SELECT Employee_Name As Employee, Salary As Salary FROM Table_Name ORDER BY Salary DESC LIMIT M, 1);

Where, M=N-1


Example:

SELECT Name AS Employee, salary_in_$ AS Salary FROM Employees ORDER BY salary DESC LIMIT 1,1;


That's It!

0 comments

Comments


bottom of page