SQL Query to Find Nth Highest Salary of Employee

SQL Query. To find Nth highest salary is a very common interview question if you are going for the role at junior level. Most of the people learn it character by character, but few understand how this query works. How good or bad its performance is? In this post, we will learn these things. I am using MySQL database for demonstration.

1. Create database schema and populate table

Lets create a simple example of Employee table. We will populate this table with id, and and salary of employees. We will write the query to find nth highest salary on this table.

Create a new database schema.

Populate the table with test data.

2. SQL query to find nth highest salary

So as most of us know, query is written like this for finding nth highest salary. In below query we see how to find max salary in sql without using max function.

Here, replace the 'n' with any number. For example, if you have to find 6th highest salary , then replace n with 6.

Above query will produce below result.

SQL Query

3. How the query works

As we can see this query involves use of an inner query. Inner queries can be of two types. Correlated and uncorrelated queries. Uncorrelated query is where inner query can run independently of outer query, and correlated query is where inner query runs in conjunction to outer query. Our nth highest salary is an example of correlated query.

Lest understand first that the inner query executes every time, a row from outer query is processed. Inner query essentially does not do any very secret job, it only return the count of distinct  salaries which are higher than the currently processing row’s salary column. Anytime, it find that salary column’s value of current row from outer query, is equal to count of higher salaries from inner query, it returns the result.

4. Performance analysis

As we learned above that inner query executes every time, one row of outer query is processed, this brings a lot of performance overhead, specially if the number of rows are too big.

To avoid this, one should use DB specific keywords to get the result faster. For example in SQL server, one can use key word TOP like this.

How to find nth highest salary in sql server.

Happy Learning !!

Anh Trường IT : anhtruongit.com
Code Hay : codehay.pro
Source : https://howtodoinjava.com/sql/sql-query-find-nth-highest-salary/


Nicholas Andrew

Nicholas Andrew

My name's Quang Trường, from Ha Noi My favorite: Create Website, Software,... Phone: 0862020654 Mail: admin@codehay.pro

2 Replies to “SQL Query to Find Nth Highest Salary of Employee

Leave a Reply

Your email address will not be published. Required fields are marked *