Talentd
FleetCode
Make and follow sheets.Sign in

Nth Highest Salary solution and explanation

MediumDatabase4 min read40.5% acceptanceUpdated 9 Apr 2026
LeetCode 177: Nth Highest Salary [SQL]Frederik Müller · 6:40 · 27K viewsWatch on YouTube
9 more videos on this problem
  1. LeetCode 177: Nth Highest Salary [SQL]Frederik Müller · 6:40 · 27K views
  2. LeetCode Medium 177 "Nth Highest Salary" Amazon Bloomberg Interview SQL Question With ExplanationEveryday Data Science · 6:35 · 10K views
  3. How to find Nth highest salary from a table | Leetcode 177 | top 10 SQL interview questionthecodingworld · 5:53 · 5K views
  4. Leetcode 177 - Nth Highest Salary - Python Solution | FAANG InterviewsEveryday Data Science · 8:06 · 1K views
  5. 177. Nth Highest Salary - LeetCode MySQL SolutionCode with Carter · 3:16 · 1K views
  6. SQL - Nth Highest Salary | Leetcode 177Wrt Tech · 4:22 · 991 views
  7. LeetCode in MySQL 177 Nth Highest Salary - Michelle小梦想家 (English Version)Michelle小梦想家 · 8:57 · 722 views
  8. LeetCode 177: Nth Highest Salary (SQL Medium)Big Tech Mindset · 10:13 · 655 views
  9. 30 Days of Pandas Day 10 | Nth Highest Salary | LeetCode 177DevTechMinds · 6:52 · 526 views
  10. Leetcode Database 177. Nth Highest Salary, Medium, SQLiCode · 5:32 · 159 views

The problem

Table: Employee

+-------------+------+
| Column Name | Type |
+-------------+------+
| id          | int  |
| salary      | int  |
+-------------+------+
id is the primary key (column with unique values) for this table.
Each row of this table contains information about the salary of an employee.

Write a solution to find the nth highest salary from the Employee table. If there is no nth highest salary, return null.

The result format is in the following example.

Example 1:

Input: 
Employee table:
+----+--------+
| id | salary |
+----+--------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
+----+--------+
n = 2
Output: 
+------------------------+
| getNthHighestSalary(2) |
+------------------------+
| 200                    |
+------------------------+

Example 2:

Input: 
Employee table:
+----+--------+
| id | salary |
+----+--------+
| 1  | 100    |
+----+--------+
n = 2
Output: 
+------------------------+
| getNthHighestSalary(2) |
+------------------------+
| null                   |
+------------------------+

Approach overview

Problem Overview: Given an Employee table containing salaries, return the Nth highest distinct salary. If the table does not contain N unique salaries, the query should return NULL. The main challenge is handling duplicate salaries while correctly identifying the Nth rank.

Approach 1: ORDER BY with LIMIT and OFFSET (Time: O(n log n), Space: O(1))

This approach sorts all salaries in descending order and skips the first N-1 distinct entries using LIMIT and OFFSET. The query typically wraps the ordered results inside a subquery and selects the Nth row. Sorting dominates the cost, giving O(n log n) time complexity, while the query itself uses constant extra space.

The key detail is ensuring duplicate salaries don't affect ranking. This is usually handled with DISTINCT before applying the sort. The database engine performs the sort operation, then offsets rows until it reaches the desired position. This solution is concise and works well when you simply need the Nth value from a sorted dataset.

Problems like this commonly appear in SQL and database interview rounds because they test understanding of sorting, filtering, and result pagination.

Approach 2: Subquery with DENSE_RANK Window Function (Time: O(n log n), Space: O(n))

This method assigns a rank to each salary using the DENSE_RANK() window function ordered by salary descending. Employees with the same salary receive the same rank, which naturally handles duplicates. After ranking, a subquery filters rows where rank = N.

The database first sorts salaries to compute the window function, which takes O(n log n) time. Storing ranking metadata requires additional memory, leading to O(n) space. Despite this overhead, the logic is clearer and explicitly models the ranking problem.

Window functions are heavily used in analytical queries and appear frequently in advanced SQL window function problems. This approach scales well when additional ranking logic or grouped analytics are required.

Recommended for interviews: Both solutions are valid, but interviewers often prefer the DENSE_RANK() solution because it demonstrates strong knowledge of SQL window functions and ranking semantics. The LIMIT/OFFSET approach shows you understand sorting and pagination, but the ranking-based solution better handles duplicates and mirrors how real analytical queries are written.

Approach 1: Use SQL Query with LIMIT and OFFSET for Nth Highest Salary

This approach uses the SQL query constructs to fetch the nth highest salary directly from the database. We will utilize ORDER BY, DISTINCT, LIMIT, and OFFSET to achieve this.

Steps:

  • First, eliminate duplicate salaries using SELECT DISTINCT.
  • Sort the result in descending order using ORDER BY salary DESC.
  • Use LIMIT and OFFSET to skip the first n-1 results and take the nth result if it exists.
# Placeholder function for SQL query in Python
def get_nth_highest_salary_sql(n):
    return f"SELECT DISTINCT salary FROM Employee ORDER BY salary DESC LIMIT 1 OFFSET {n-1}"

# Execute this query using a Python SQL library like sqlite3 or SQLAlchemy.
/* Placeholder function for SQL query in Java */
public String getNthHighestSalary_SQL(int n) {
    return "SELECT DISTINCT salary FROM Employee ORDER BY salary DESC LIMIT 1 OFFSET " + (n-1);
}

// Use JDBC for executing this query in a database environment.
/* Placeholder function for SQL query in C++ */
#include <iostream>
#include <string>

std::string getNthHighestSalary_SQL(int n) {
    return "SELECT DISTINCT salary FROM Employee ORDER BY salary DESC LIMIT 1 OFFSET " + std::to_string(n-1);
}

/* Run this query in a SQL database system using a library like MySQL Connector/C++. */
// Placeholder function for SQL query in JavaScript
function getNthHighestSalarySQL(n) {
    return `SELECT DISTINCT salary FROM Employee ORDER BY salary DESC LIMIT 1 OFFSET ${n - 1}`;
}

// Use Node.js MySQL or another SQL execution environment to run this query.
/* As SQL query requires running in a database environment, this is a placeholder function */
#include <stdio.h>

/* In a database environment, use this SQL query directly */
const char* getNthHighestSalary_SQL(int n) {
    return "SELECT DISTINCT salary FROM Employee ORDER BY salary DESC LIMIT 1 OFFSET ?";
}

/* Explanation: This function returns the SQL query as a string. The actual execution needs to be done in an SQL environment. */
/* Placeholder function for SQL query in C# */
public string GetNthHighestSalarySQL(int n)
{
    return $"SELECT DISTINCT salary FROM Employee ORDER BY salary DESC LIMIT 1 OFFSET {n-1}";
}

// Implement actual execution using ADO.NET or any ORM.

This Python function generates a SQL query string. Execute this query using libraries like sqlite3 or SQLAlchemy in a database context.

Complexity
  • Time Complexity: O(n)
  • Space Complexity: O(1)
Try this approach in the editor

Approach 2: Use Subquery with DENSE_RANK to Identify Nth Highest Salary

In this approach, we will use the DENSE_RANK() window function available in SQL to assign ranks to salaries based on their value.

Steps:

  • Rank salaries using DENSE_RANK by partitioning properly.
  • Select the salary where the rank matches the input n.
  • This accounts for duplicate values effectively while ranking.
# Advanced SQL execution placeholder in Python
def get_nth_highest_salary_dense_rank_sql(n):
    return f"SELECT salary FROM (SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) as rank FROM Employee) Ranked WHERE rank = {n}"

# Use this query in database environments supporting SQL window functions.
/* Execute this advanced SQL using Java's JDBC */
public String getNthHighestSalary_DenseRankSQL(int n) {
    return "SELECT salary FROM (SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) as rank FROM Employee) as Ranked WHERE rank = " + n;
}

// Requires database back-end support for window functions.
/* Placeholder for advanced SQL execution in C++ */
#include <iostream>
#include <string>

std::string getNthHighestSalary_DenseRankSQL(int n) {
    return "SELECT salary FROM (SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) as rank FROM Employee) as Ranked WHERE rank = " + std::to_string(n);
}

/* Execute within SQL database systems supporting advanced SQL functions */
// Placeholder for executing advanced SQL with JavaScript
function getNthHighestSalaryDenseRankSQL(n) {
    return `SELECT salary FROM (SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) as rank FROM Employee) Ranked WHERE rank = ${n}`;
}

// Implement execution in SQL supported environments.
/* Placeholder function for advanced SQL query in C */
#include <stdio.h>

/* In an actual database system, execute the following SQL statement */
const char* getNthHighestSalary_DenseRankSQL(int n) {
    return "SELECT salary FROM (SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) as rank FROM Employee) as Ranked WHERE rank = ?";
}

/* Run this SQL query within a relational database to get the result. */
/* Placeholder for executing advanced SQL in C# */
public string GetNthHighestSalaryDenseRankSQL(int n) {
    return $"SELECT salary FROM (SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) as rank FROM Employee) Ranked WHERE rank = {n}";
}

// Requires use of database frameworks capable of SQL window functions.

This Python function returns a SQL query string using DENSE_RANK to rank salaries. Execute it in a database environment for results.

Complexity
  • Time Complexity: O(n)
  • Space Complexity: O(1)
Try this approach in the editor

Approach 3: Default Approach

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
    SET N = N - 1;
  RETURN (
      # Write your MySQL query statement below.
      SELECT (
          SELECT DISTINCT salary
          FROM Employee
          ORDER BY salary DESC
          LIMIT 1 OFFSET N
      )
  );
END
Try this approach in the editor

Complexity comparison

ApproachComplexity
Use SQL Query with LIMIT and OFFSET for Nth Highest Salary
  • Time Complexity: O(n)
  • Space Complexity: O(1)
Use Subquery with DENSE_RANK to Identify Nth Highest Salary
  • Time Complexity: O(n)
  • Space Complexity: O(1)
Default Approach–

Complexity analysis

ApproachTimeSpaceWhen to Use
ORDER BY with LIMIT and OFFSETO(n log n)O(1)When you only need the Nth value after sorting and want a concise query
Subquery with DENSE_RANK Window FunctionO(n log n)O(n)When duplicate values must share the same rank or when writing analytical SQL queries

Frequently asked questions

Is Nth Highest Salary easy or hard?

Nth Highest Salary is considered a medium difficulty SQL problem. The challenge comes from handling duplicate salaries correctly and understanding ranking techniques like DISTINCT sorting or window functions.

Nth Highest Salary Python/Java solution

When solved outside SQL, languages like Python or Java typically store salaries in an array or list, remove duplicates using a set, sort in descending order, and return the Nth element. The complexity is O(n log n) due to sorting.

How to solve Nth Highest Salary in O(n)?

Pure O(n) solutions are uncommon in SQL because ranking usually requires sorting. Database engines rely on ORDER BY or window functions that internally perform O(n log n) sorting. Achieving true O(n) would require specialized indexing or precomputed ranking structures.

What is the best approach for Nth Highest Salary?

The most robust approach uses the SQL window function DENSE_RANK(). It ranks salaries in descending order and selects rows where the rank equals N. This correctly handles duplicate salaries because identical values share the same rank.

Is Nth Highest Salary asked at Google/Amazon/Meta?

Nth Highest Salary is a common SQL interview problem across companies like Amazon, Google, Meta, and Microsoft. It tests knowledge of ranking queries, DISTINCT handling, and SQL window functions such as DENSE_RANK or ROW_NUMBER.

What data structure is used in Nth Highest Salary?

The problem is solved using SQL query operations rather than traditional data structures. Internally, the database relies on sorting algorithms and ranking mechanisms like DENSE_RANK, often backed by indexes or temporary sorted structures.

What is the time complexity of Nth Highest Salary?

Most SQL solutions require sorting the salary column, which takes O(n log n) time. Window functions like DENSE_RANK() also depend on sorting internally, so they have the same overall complexity. Space complexity ranges from O(1) to O(n) depending on the query plan.

Comments

Now write it yourselfClose this page and solve Nth Highest Salary in the editor, without looking.
Practise Nth Highest Salary