Showing posts with label Subquery to find second higest salary. Show all posts
Showing posts with label Subquery to find second higest salary. Show all posts

Thursday, August 6, 2009

SQL Query: Find second highest salaried employee ?

Here's the SQL code:-

--Returns name and salary of employee assuming EMPLOYEE and SALARY are different tables with
--column ID connecting both
SELECT NAME,SALARY FROM EMPLOYEE INNER JOIN SALARY ON EMPLOYEE.ID=SALARY.ID WHERE SALARY IN(
  --following query returns required salary (Second largest in example)
   SELECT MAX(SALARY) FROM SALARY WHERE SALARY NOT IN
   (
     --follwing query returns top x(1 in example) salaries
     --replace x to 0,1,... to get highest, second highest,...
     SELECT TOP 1 SALARY FROM SALARY ORDER BY salary DESC
   )
)




SQL Query to find THIRD highest salaried employee:-

SELECT name,

       salary

FROM   employee

       INNER JOIN salary

         ON employee.id = salary.id

WHERE  salary IN (SELECT Max(salary)

                  FROM   salary

                  WHERE  salary NOT IN (SELECT   TOP 2 salary

                                        FROM     salary

                                        ORDER BY salary DESC))

Was the information useful?

Followers