title: LeetCode 177: Nth Highest Salary
body: <p>This is a famous <a href="https://leetcode.com/problems/nth-highest-salary/" rel="nofollow noreferrer">interview question</a>:</p>
  <h3>Problem</h3>
  <p>Write a SQL query to get the nth highest salary from the Employee table.</p>
  <pre><code>+----+--------+
  | Id | Salary |
  +----+--------+
  | 1  | 100    |
  | 2  | 200    |
  | 3  | 300    |
  +----+--------+
  </code></pre>
  <p>For example, given the above Employee table, the nth highest salary where n = 2 is 200. If there is no nth highest salary, then the query should return null.</p>
  <pre><code>+------------------------+
  | getNthHighestSalary(2) |
  +------------------------+
  | 200                    |
  +------------------------+
  </code></pre>
  <h3>MySQL Attempt</h3>
  <pre><code>CREATE FUNCTION getNthHighestSalary(nHighestSalary INT) RETURNS INT
  BEGIN
      SET nHighestSalary = nHighestSalary - 1;
      RETURN(
          SELECT DISTINCT salary
          FROM employee
          ORDER BY salary DESC
          LIMIT 1
          OFFSET nHighestSalary
          );
  END
  </code></pre>
  <p>What would be the most efficient query for the problem?</p>
  <h3>Reference</h3>
  <p><a href="https://leetcode.com/problems/nth-highest-salary/" rel="nofollow noreferrer">177. Nth Highest Salary</a></p>