HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / SQL / SQL Query to Find Nth Highest Salary of Employee

SQL Query to Find Nth Highest Salary of Employee

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.

Table of Contents

1. Create the schema and populate table
2. Write the query and verify the result
3. How the query works
4. Performance analysis

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.

Create schema TestSQL;

Create a new table Employee_Test.

CREATE TABLE Employee_Test
(
    Employee_ID INT,
    Employee_name Varchar(100),
    Employee_Salary Decimal (10,2)
);

Populate the table with test data.

INSERT INTO Employee_Test VALUES (1,'Anish',1000);
INSERT INTO Employee_Test VALUES (2,'Sushant',1200);
INSERT INTO Employee_Test VALUES (3,'Rakesh',1100);
INSERT INTO Employee_Test VALUES (4,'Manoj',1300);
INSERT INTO Employee_Test VALUES (5,'Amit',1400);
INSERT INTO Employee_Test VALUES (6,'Lokesh',1600);
INSERT INTO Employee_Test VALUES (7,'Maneneder',1400);
INSERT INTO Employee_Test VALUES (8,'Narendra',400);
INSERT INTO Employee_Test VALUES (9,'Kaushal',1900);
INSERT INTO Employee_Test VALUES (10,'Vikas',3400);
INSERT INTO Employee_Test VALUES (11,'Sudhir',800);

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.

SELECT *
FROM Employee_Test Emp1
WHERE ( n ) = (
                SELECT COUNT( DISTINCT ( Emp2.Employee_Salary ) )
                FROM Employee_Test Emp2
                WHERE Emp2.Employee_Salary >= Emp1.Employee_Salary
            )

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

SELECT *
FROM Employee_Test Emp1
WHERE (6) = (
SELECT COUNT( DISTINCT ( Emp2.Employee_Salary ) )
FROM Employee_Test Emp2
WHERE Emp2.Employee_Salary >= Emp1.Employee_Salary
)

Above query will produce below result.

nth_highest_salary1-3067572

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.

SELECT TOP 1 EMPLOYEE_SALARY
FROM
(
    SELECT DISTINCT TOP N EMPLOYEE_SALARY
    FROM EMPLOYEE_TEST
    ORDER BY EMPLOYEE_SALARY DESC
) A
ORDER BY EMPLOYEE_SALARY
WHERE N > 1

Happy Learning !!

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Naveen

    January 24, 2020

    Very sorry to say that this work only if there are all distinct salaries in the table.

  2. Sangita

    December 11, 2019

    ORDER BY should be after WHERE clause.

  3. Roopa

    March 24, 2018

    Please give us pseudo code for Java and nothing from database

  4. Ajay Pandey

    September 16, 2014

    very nice explanation..
    TOP is not working in postgres database so we have to go with DISTINCT.
    if any another way is there to find nth highest please do mention.

  5. Ram Krishna Dixit

    June 13, 2014

    Hi Nice Article,
    Just want to mention that in sybase
    Getting nth salary using top is not working in sybase
    so I have to go with first approach

    SELECT *
    FROM Employee_Test Emp1
    WHERE ( n ) = (
    SELECT COUNT( DISTINCT ( Emp2.Employee_Salary ) )
    FROM Employee_Test Emp2
    WHERE Emp2.Employee_Salary >= Emp1.Employee_Salary
    )

    • Lokesh Gupta

      June 13, 2014

      Thanks for adding your findings.

  6. vijay bhatt

    February 13, 2014

    /*for 3rd highest salary n=2, for 2nd highest salary n=1, nth highest salary n=n-1*/
    SELECT DISTINCT(Salary) FROM employee ORDER BY Salary DESC LIMIT n,1

  7. Neha Insa

    November 22, 2013

    SELECT first_name FROM tbl_author_master WHERE author_id IN
    (SELECT author_id FROM tbl_mpstrak_journal_manuscript_author WHERE manuscript_id IN
    (SELECT manuscript_id FROM tbl_mpstrak_journal_manuscript));

    convert this sql command in join* sql command::::i m not getting corresponding answer in joins?????

    • Neha Insa

      November 22, 2013

      i tried it,,, but not getting::::::::::
      SELECT
      am.first_name
      FROM
      tbl_mpstrak_journal_manuscript jms JOIN tbl_mpstrak_journal_manuscript_author msa
      JOIN tbl_author_master am
      WHERE am.author_id =msa.author_id AND jms.manuscript_id=msa.manuscript_id;

      • Neha Insa

        November 22, 2013

        i want it wid ON clauses

  8. Shabher

    November 15, 2013

    how to find out 5th max sal from only one employee table……

    • Mohamed Mukhthar

      December 28, 2014

      here is common query for any highest salary(nth). for ex if the table name is emp and the column name is sal

      select * from emp
      where sal=(select sal from
      (select sal from(select sal from(select distinct sal from emp order by sal desc)
      where rownum<=n)order by sal)where rownum = 1);

  9. Bobby

    July 16, 2013

    Wonderful information here. Thank you.

  10. Mithilesh Jha

    March 7, 2013

    A big thanks for such a nice query 🙂

  11. Manas Mani Tripathi

    January 10, 2013

    Your query takes more resources. Correct way to wite this query is :

    SELECT MIN(SALARY) FROM EMP WHERESALARY IN (SELECT DISTINCT TOP N SALARY FROM EMP ORDER BY SALARY DESC)

    • Lokesh Gupta

      January 10, 2013

      Manas, if you look at the last section of the post.. similar query is mentioned there.. but problem is .. its database specific. TOP keyword is not supported by all databases.. I proposed a generic query which is supported by all databases.

      • Tanmoy

        February 20, 2014

        SELECT TOP 1 EMPLOYEE_SALARY
        FROM
        (
        SELECT DISTINCT TOP N EMPLOYEE_SALARY
        FROM EMPLOYEE_TEST
        ORDER BY EMPLOYEE_SALARY DESC
        ) A
        ORDER BY EMPLOYEE_SALARY
        WHERE N > 1

        This Query is not working in my database. It gives error in SQL* Plus like

        SELECT TOP 1 EMPLOYEE_SALARY
        *
        ERROR at line 1:
        ORA-00923: FROM keyword not found where expected

        Please suggest me some solution.

      • Ravi RANAJAN

        May 29, 2014

        why top keyword is not supported by all database????????..

        • Lokesh Gupta

          May 29, 2014

          Can’t answer on behalf of all database vendors.. 😉

        • Mohamed Mukhthar

          December 28, 2014

          Each and every Query language (SQL*plus,t-sql,win-sql) were inherited from ANSI SQL .So 70% of all sql languages are similar except these(top,etc) which is patented by microsoft (MS-SQL-SERVER). These are extended features of particular language.

Comments are closed on this article!

Search Tutorials

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)