You are on page 1of 3

SQL SERVER Interview Questions

1. SQL Query to find the second highest salary?

Consider below simple table:


Name Salary
---------------
Employee1 100000
Employee2 1000000
Employee3 40000
Employee4 500000
How to find the employee whose salary is second highest. For example, in above table,
“Employee4” has the second highest salary as 500000.
Below is simple query to find the employee whose salary is highest.
SELECT name, MAX(salary) as salary FROM employee
We can nest the above query to find the second largest salary.
SELECT name, MAX(salary) AS salary
FROM employee
WHERE salary < (SELECT MAX(salary)
FROM employee);
There are other ways also,
SELECT name, MAX(salary) AS salary
FROM employee
WHERE salary IN
(SELECT salary FROM employee MINUS SELECT MAX(salary)
FROM employee);
SELECT name, MAX(salary) AS salary
FROM employee
WHERE salary (SELECT MAX(salary)
FROM employee);
Using CTE method:
IN SQL Server using Common Table Expression or CTE, we can find the second highest salary:
WITH T AS
(
SELECT *
DENSE_RANK() OVER (ORDER BY Salary Desc) AS Rnk
FROM Employees
)
SELECT Name
FROM T
WHERE Rnk=2;
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

You might also like