🔥 LeetCode SQL: Nth Highest Salary Explained in 5 Minutes (With Edge Case!)

preview_player
Показать описание
🚀 In this video, we solve LeetCode SQL Problem #177: "Nth Highest Salary" using a powerful and clean approach — by creating a custom SQL function with `DENSE_RANK()`!

🎯 Objective:
Write a SQL function `getNthHighestSalary(N INT)` that returns the N-th highest distinct salary from the Employee table. If there are fewer than N distinct salaries, return NULL.

📌 SQL Concepts Covered:
- Creating user-defined functions in MySQL
- Using `DENSE_RANK()` to handle duplicate salaries
- Subqueries and inline ranking
- Returning NULL for missing data (edge case handling)

🛠️ Solution Overview:
We use a subquery with `DENSE_RANK()` ordered by salary (ascending or descending, depending on use case), wrap it inside a custom function, and return the salary where the rank matches the input `N`.

✅ Function Syntax Used:
```sql
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
RETURN (
SELECT salary
FROM (
SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk
FROM Employee
) AS ranked
WHERE rnk = N
);
END

📘 Example:
If the Employee salaries are [100, 200, 300] and N = 2, the function returns 200. If only one distinct salary exists and N = 2, it returns NULL.

📎 Problem Link:

🔍 Great for SQL interview prep and mastering window functions!

👍 Like the video if this helped you, and subscribe for more SQL tutorials, LeetCode walk-throughs, and data interview prep content!

#LeetCode #SQL #WindowFunctions #DENSE_RANK #MySQL #DataEngineering #TechInterview #SQLTutorial #NthHighestSalary #LeetCodeSQL
Рекомендации по теме
visit shbcf.ru