Sunday, September 27, 2020

Find out the name and salary of employee with 3rd highest salary

Using Postgres

CREATE TABLE EMPLOYEE (
ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
SALARY REAL
)

INSERT INTO COMPANY (ID, NAME, SALARY,)
VALUES (2, 'Allen', 25000);

INSERT INTO EMPLOYEE (ID, NAME, SALARY)
VALUES (1, 'Rohit', 50000);

INSERT INTO EMPLOYEE (ID, NAME, SALARY)
VALUES (3, 'Krishna', 70000);

INSERT INTO EMPLOYEE (ID, NAME, SALARY)
VALUES (4, 'Ram', 80000);

INSERT INTO EMPLOYEE (ID, NAME, SALARY)
VALUES (5, 'Ganesh', 90000);

SELECT * FROM EMPLOYEE



To find out 3rd highest salary in Employee table.
Here  3rd highest salary is 70000.

-- Step 1 - Let's see all salaries 

select salary from employee



--Step 2 - Arrange salary in descending /decreasing order

select salary from employee order by salary desc


--Step 3 - Put a limit of 3 

select salary from employee order by salary desc limit 3



--Step 4 - Arrange the result in ascending order and limit to 1 to get the 3rd highest salary

select name,salary from (select name,salary from employee order by salary desc limit 3) A order by salary limit 1

Here A is alias for table



https://sqlformat.org/


No comments:

Post a Comment