Using CTE and Dense_Rank [ beats 95% - 288ms ] with Explanation
The DENSE_RANK() is a window function that assigns ranks to rows in partitions with no gaps in the ranking values.\n\n If two or more rows in each partition hav
* The **DENSE_RANK()** is a window function that assigns ranks to rows in partitions with no gaps in the ranking values.\n\n* If two or more rows in each partition have the same values, they receive the same rank. The next row has the rank increased by one.\n\n* Different from the RANK() function, the DENSE_RANK() function always generates consecutive rank values.\n\n**DENSE_RANK() OVER(PARTITION BY.... ORDER BY....) works like this**\n\n* First, the PARTITION BY clause divides the result set produced by the FROM clause into partitions.\n* Then, The ORDER BY specifies the order of rows in each partition.\n* Finally, the DENSE_RANK() function is applied to the rows in the specified order of each partition. It resets the rank when the partition boundary is crossed.\n \n```\nCREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT\nBEGIN\n\n  RETURN (\n      # Write your MySQL query statement below.\n      \n      WITH CTE AS\n        (\n            SELECT DISTINCT salary,\n            DENSE_RANK() OVER(ORDER BY salary DESC) AS dr\n            FROM Employee\n        )\n        \n        SELECT salary \n        FROM CTE\n        WHERE dr = N\n        \n      \n      \n  );\nEND\n```\n\n* Here I didn\'t Use **PARTITION BY** because there was no need to assign rank to salaries on the basis of some partition so the **DENSE_RANK()** function treated the whole result set as a single Partition\n \n*  The **ORDER BY** clause sorted the salaries in descending order. Then, the DENSE_RANK() \nfunction assigned a rank to each employee by his/her salary amount.\n\n* and, Finally in Where clause **[ dr = N ]** , it will match the rank with number **N** and will return the salary accordingly \n\n* if there **Nth** same salaries, even then this code will work because i am using Dense rank which will assign same rank to same values / salaries \n\nIf there is any Improvement that can be done or if there is any optimised way of doing it then feel free to comment and Discuss\n\nThanks for Visiting, I hope my Solution solved your Problem :)
['MySQL']