Skip to content

Conversation

@Priyam2773
Copy link
Owner

🧠 Intuition

To find the Nth highest salary from the Employee table, we can use SQL’s LIMIT and OFFSET clauses. However, since SQL doesn’t have a built-in direct “Nth highest” function, we must order the salaries in descending order, skip the top N−1, and pick the next one.

We also handle the case where the Nth highest salary does not exist (e.g., fewer distinct salaries than N).

🧩 Approach

Select distinct salaries from the Employee table.

Order them in descending order.

Use LIMIT 1 OFFSET N-1 to get the Nth highest.

Use IFNULL to handle missing results (return NULL if not found).

💻 Code Solution (C++)
// Problem 177. Nth Highest Salary.cpp
// LeetCode Database Problem

#include <bits/stdc++.h>
using namespace std;

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

string getNthHighestSalary(int N) {
string query =
"SELECT DISTINCT Salary FROM Employee "
"ORDER BY Salary DESC "
"LIMIT 1 OFFSET " + to_string(N - 1) + ";";
return query;
}

int main() {
int N;
cin >> N;
cout << getNthHighestSalary(N) << endl;
return 0;
}

🧾 Related Issues

Closes SjxSubham#177

By submitting this PR, I confirm that:

This is my original work not totally AI generated

I have tested the solution thoroughly on LeetCode

I have maintained proper PR description format

This is a meaningful contribution, not spam

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants