SQL Leetcode: 177. Nth Highest Salary

Pallavi Mirajkar Dantkale
1 min readMar 29, 2021

--

177. Nth Highest Salary

Medium

599451Add to ListShare

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

+----+--------+
| Id | Salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+----+--------+

For example, given the above Employee table, the nth highest salary where n = 2 is 200. If there is no nth highest salary, then the query should return null.

+------------------------+
| getNthHighestSalary(2) |
+------------------------+
| 200 |
+------------------------+
  1. Using Correlated Subquery

CREATE FUNCTION getNthHighestSalary(N INT)

RETURNS INT
BEGIN
RETURN (
SELECT
Salary as getNthHighestSalary
from Employee e1
where N-1 = (Select COUNT(DISTINCT salary) from employee e2
WHERE e2.salary > e1.salary)
UNION
Select null
limit 1

);
END

2. Using DENSE_RANK()

CREATE FUNCTION getNthHighestSalary(N INT)

RETURNS INT
BEGIN
RETURN (
WITH CTE AS (
SELECT
Salary,
DENSE_RANK() OVER (ORDER BY SALARY DESC) as rank_salary
from Employee
)
SELECT distinct SALARY AS getNthHighestSalary
FROM CTE
WHERE rank_salary = N

UNION
Select null
limit 1

);
END

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Pallavi Mirajkar Dantkale
Pallavi Mirajkar Dantkale

Written by Pallavi Mirajkar Dantkale

QA Engineer / Data Analyst — Highly committed to Quality Assurance and data analysis, advocate for quality and add the right value to the organization.

No responses yet

Write a response