Nth Highest salaryFinding the Nth highest salary( 2nd, 3rd, or nth highest) in a table is the most important and common question asked in various interviews. Here we will show you the best and easiest way to write SQL queries to find nth highest salary in a table. To show this, we are using Table Emp having employee details like EID, ENAME, and SALARY. Data present in the Emp Table is shown below: Table Name: Emp
The SQL query to calculate second highest salary in database table name as EmpQuery: 1 Output: MIN(SALARY) ----------- 37000 The Structure and data in Emp TableThe Output ScreenLet us understand how this query is working:The SQL query to calculate second highest salary in database table name as EmpQuery: 2 Output: ENAME SALARY Rank ------------ ---------- ---------- ravi 37000 2 Let us understand how this query is working:The SQL query to calculate second highest salary in database table name as EmpLet's say the job is to calculate the Nth highest salary of employee from the above table. The procedure is as follows:
Query No: 3 The above SQL query will find out the details of the emp with the nth highest salary. Let's see the working of the above SQL query in detail:
The processing done by server is that, it starts with most inner query, the query: "select distinct TOP 5 salary from emp order by salary desc" will generate following result:
From above result it is verified that the required Fifth highest salary is 28000.
Working of queryAs these queries are nested queries so this query involves the use of an inner query. There are two versions of Inner queries. Correlated and Uncorrelated queries. Uncorrelated queries are those where the inner query can run independently of the outer query, and the correlated query is those where the inner query runs in conjunction with the outer query. The query we took to calculate nth highest salary is an example of a correlated query. Performance analysis of SQL queryFrom the above, we have learned that the inner query executes every time, single row of the outer query is processed, this ultimately brings a lot of performance overhead, especially when the number of rows is very large. To avoid this, it is recommended to use Data Base specific keywords to get the result faster.
Next Topic12 Codd?s Rules
|