Nth Highest Salary

medium sorting database

Problem

Write a SQL function getNthHighestSalary(N) that returns the Nth highest distinct salary from Employee, or NULL when fewer than N distinct salaries exist.

SQL: SELECT DISTINCT salary FROM Employee ORDER BY salary DESC LIMIT 1 OFFSET N-1;

Inputsalaries = [100, 200, 300], N = 2
Output200

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
  RETURN (SELECT DISTINCT salary FROM Employee
          ORDER BY salary DESC LIMIT 1 OFFSET N-1);
END
Time: O(n log n) Space: O(n)