Add SQL query for second highest salary #2
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
🧠 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