Skip to main content

SQL Problem - Find 3rd highest employee salary

SQL Problem - Find 3rd highest employee salary


Problem Statement

Create an SQL query to retrieve all details of employees who receive the third-highest salary.
Ensure the query returns all columns from the employees table. Additional Requirement: Do not use the LIMIT keyword in your query.

Sample Input:




Table: employees:



Sample Output


Solution:

Approach 1: Using Sub Query:


select * from employees where salary = (
select distinct(salary) from employees  order by salary
desc limit 1 offset 2)


  • The subquery finds the third-highest distinct salary by ordering the salaries in descending order, skipping the first two, and then selecting the next one.
  • The main query then retrieves all employees who have this third-highest salary.

  • Approach 2: Using Nested Inner Queries

    SELECT * FROM EMPLOYEES WHERE SALARY =(
        SELECT MAX(SALARY) FROM EMPLOYEES WHERE SALARY <(
            SELECT MAX(SALARY) FROM EMPLOYEES WHERE SALARY < (
                SELECT MAX(SALARY) FROM EMPLOYEES)  
        )
    )
        
    1. Innermost Subquery:
      • SELECT MAX(salary) FROM employees finds the highest salary.
    2. Middle Subquery:
      • SELECT MAX(salary) FROM employees WHERE salary < (SELECT MAX(salary) FROM employees) finds the second-highest salary by looking for the maximum salary that is less than the highest salary found in the innermost subquery.
    3. Outermost Subquery:
      • SELECT MAX(salary) FROM employees WHERE salary < (SELECT MAX(salary) FROM employees WHERE salary < (SELECT MAX(salary) FROM employees)) finds the third-highest salary by looking for the maximum salary that is less than the second-highest salary found in the middle subquery.
    4. Main Query:
      • The main query selects all columns from the employees table where the salary matches the third-highest salary found in the outermost subquery.

    Approach 2: Using CTE:

    WITH RankedSalaries AS (
        SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rank
        FROM employees
    )
    SELECT *
    FROM employees
    WHERE salary = (
        SELECT salary
        FROM RankedSalaries
        WHERE rank = 3
    );

    In this alternative approach:

    1. Common Table Expression (CTE): The CTE RankedSalaries assigns a rank to each distinct salary using the DENSE_RANK() window function.
    2. Rank Filter: The subquery inside the WHERE clause selects the salary where the rank is 3.
    3. Main Query: The outer query retrieves all employee details where their salary matches the third-highest salary.


    Comments

    Popular posts from this blog

    SQL Constraints In DBMS

      Do we need constraints? SQL Constraints are set of rules and restrictions which are applied to the columns or table of the database. This constraint ensures below points. Data consistency No accidental data loss by deleting reference data. Reduce data redundancy. Table Level Constraints PRIMARY KEY FORIEGN KEY PRIMARY KEY Primary Key constraint ensure that column doesn't contain NOT NULL value and unique. It will be used to identify particular row from the table. Table is by default index on the primary key column. Below sample code creates EMP_ID as primary key for EMPLOYEE table which is auto increment by one every time a new record inserted in the table. CREATE TABLE EMPLOYEE (     EMP_ID INT PRIMARY KEY AUTO INCREAMENT NOT NULL ,     NAME   VARCHAR ( 200 ),      EMAIL VARCHAR ( 200 ), AGE INT,     PHONE_NUMBER VARCHAR ( 15 )     ISACTIVE CHAR ( 1 ) ) FOREIGN KEY Foreign Key is used to relate two tables. Th...

    Different Keys In DBMS

    Do we need key? DBMS (Database Management System)   stores large amount of data in such a way so that it will be easy to read, write and secure in efficient manner. It uses table format to organize data and store data in column and row format. However, data is stored in unordered format and difficult to identify unique record from the table. Let us understand this concept with two simple tables which represent data about the employees and their respective department. Employee Table Code Name Email Address Dept. Code Phone Number Address 01 John Smith j.smith@example.com 3 123-456-7890 123 Main St, City, Country 02 Jane Doe j.doe@example.com 1 987-654-3210 456 Elm St, City, Country 03 David Johnson d.johnson@example.com 2 555-123-4567 789 Oak St, City, Country ...