Sql coding exercise nth highest salary technology of computing. If there is no nth highest salary, then the query should. Solution to finding the 2nd highest salary in sql select maxsalary from employee. Salary 750 will be 2, or n1, hence this row will be returned. Sql query to find nth highest salary tutorial gateway. Write a sql query to find nth highest salary, 2nd highest salary, or third highest salary is the most common sql interview question. For example, given the above employee table, the nth highest salary where n 2 is 300. Btw, if you are new to sql and just learning these query from interviews sake then i suggest you to first read a good book on sql e.
This is the best place to expand your knowledge and get prepared for your next interview. Since we want to get the nth highest salary, it is necessary to sort the table based on salary, from highest to lowest, so that we can easily pick the nth from the highest. If there is no second highest salary, then the query should return null. For example, given the above employee table, the nth highest salary where n 2 is 200. In mysql queries, it is not straightforward to only query the nth record as we do in an array an1, for that, we can use limit and offset. Example, if we are to find 3rd largest salary n3 from 800, 700, 750, the subquery for 1st row would be select countdistinctemp2. Select top 1 salary from employee where salary in select top n distinct salary from employee order by. Second highest salary in mysql and sql server leetcode. Write a sql query to get the nth highest salary from the employee table. Type name latest commit message commit time failed to load latest commit information. In addition, i would like to provide a solution using top and limit and its with subquery but leetcode s compiler does not support it. In this article we will show you the best possible way to write sql server query to find nth highest salary with example. Find file copy path fetching contributors cannot retrieve contributors at this time.
You can write sql query in any of your favorite database e. Level up your coding skills and quickly land a job. How to find nth highest salary from a table leetcode 177. Find nth highest salary massive technical interviews tips. Accpted solution for the nth highest salary leetcode discuss. If there is no nth highest salary, then the query should return null.
793 1257 1004 1445 889 1549 46 28 279 403 1345 859 1104 1380 1174 1382 845 671 456 418 1357 153 240 467 629 1092 678 777 764 128 501 1032 721