Second Highest Salary - sql

Write a SQL query to get the second highest salary from the Employee table.
| Id | Salary |
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
For example, given the above Employee table, the query should return 200 as the second highest salary. If there is no second highest salary, then the query should return null.
| SecondHighestSalary |
| 200 |
This is a question from Leetcode, for which I entered the following code:
SELECT CASE WHEN Salary = ''
THEN NULL
ELSE Salary
END AS SecondHighestSalary
FROM (SELECT TOP 2 Salary
,ROW_NUMBER() OVER (ORDER BY Salary DESC) AS Num
FROM Employee
ORDER BY Salary DESC) AS T
WHERE T.Num = 2
It says that the query does not return NULL if there's no value for second highest salary.
For eg. if the table is
| Id | Salary|
| 1 | 100 |
The query should return
|SecondHighestSalary|
| null |
and not
|SecondHighestSalary|
| |

Solution to the Leetcode 2nd highest salary problem is:
Select
Max(Salary) AS SecondHighestSalary
from Employee
where Salary < (
Select Max(Salary) from Employee
);

In case of ties you want the second highest distinct value. E.g. for values 100, 200, 300, 300, you want 200.
So get the highest value (MAX(salary) => 300) and then get the highest value less than that:
select max(salary) from mytable where salary < (select max(salary) from mytable);

Using window functions, utilizing NTH_VALUE gives a clean answer
SELECT (
SELECT NTH_VALUE(Salary, 2) OVER(ORDER BY Salary DESC) AS SecondHighestSalary
FROM Employee
GROUP BY Salary
LIMIT 1 OFFSET 1 ) AS SecondHighestSalary
;
Detailed Break-Down:
The outer SELECT Statement is required to get NULL value incase a value was not found (second rank is not present for example, or table only has one row)
NTH_VALUE(Salary, 2) is basically saying, look at each group (in our case it divides the table based on groups of Salary) and for each group add a column that lists the second highest value, for every row within the same group from that new column, we want to pick the second most paid (so only second row)
NTH_VALUE() OVER(ORDER BY) is in ASC order by default, make sure you explicit the DESC order
NTH_VALUE() merely gives the order to the rows within each group (here Salary) incase of two similar salaries in the same salary group it will give them separate ranks (ex 1 and 2) even if they have same value in the same group, For this use GROUP BY () statement
Because NTH_VALUE() merely gives the order to the columns, based on a group USE LIMIT 1 to get just one value (top value) and OFFSET 1 (to make that top value our targeted second most paid)

you should be able to do that with OFFSET 1/FETCH 1:
https://technet.microsoft.com/en-us/library/gg699618(v=sql.110).aspx

SELECT id, MAX(salary) AS salary
FROM employee
WHERE salary IN
(SELECT salary FROM employee MINUS SELECT MAX(salary)
FROM employee);
You can try above code to find 2nd maximum salary.
The above code uses MINUS operator.
For further reference use the below links
https://www.techonthenet.com/sql/minus.php
https://www.geeksforgeeks.org/sql-query-to-find-second-largest-salary/

You can use RANK() function to rank the values for Salary column, along with a CASE statement for returning NULL.
SELECT
CASE WHEN MAX(SalaryRank) = 1 THEN NULL ELSE Salary as SecondHighestSalary
FROM
(
SELECT *, RANK()OVER(ORDER BY Salary DESC) As SalaryRank
FROM Employee
) AS Tab
WHERE SalaryRank = 2
It would be better to use the DENSE_RANK() function so that ranks don't get skipped whenever there is a tie for a position.

I would use DENSE_RANK() & do LEFT JOIN with employee table :
SELECT t.Seq, e.*
FROM ( VALUES (2)
) t (Seq) LEFT JOIN
(SELECT e.*,
DENSE_RANK() OVER (ORDER BY Salary DESC) AS Num
FROM Employee e
) e
ON e.Num = t.Seq;

While you can use a CTE (from MSSQL 2005 or newer) or ROWNUMBER the easiest and more "portable" way is to just order by twice using a subquery.
select top 1 x.* from
(select top 2 t1.* from dbo.Employee t1 order by t1.Salary) as x
order by x.Salary desc
The requisite to show null when there's not a second bigger salary is a bit more tricky but also easy to do with a if.
if (select count(*) from dbo.Employee) > 1
begin
select top 1 x.* from
(select top 2 emp.* from dbo.Employee emp order by emp.Salary) as x
order by x.Salary desc
end
else begin
select null as Id, null as Salary
end
Obs:. OP don't said what to do when the second largest is a tie with the first but using this solution is a simple matter of using a DISTINCT in the IF subquery.

Here is the easy way to do this
SELECT MAX(Salary) FROM table WHERE Salary NOT IN (SELECT MAX(Salary) FROM table);

You can try this for getting n-th highest salary, where n = 1,2,3....(int)
SELECT TOP 1 salary FROM (
SELECT TOP n salary
FROM employees
ORDER BY salary DESC) AS emp
ORDER BY salary ASC
Hope this will help you. Below is one of the implementation.
create table #salary (salary int)
insert into #salary values (100), (200), (300)
SELECT TOP 1 salary FROM (
SELECT TOP 2 salary
FROM #salary
ORDER BY salary DESC) AS emp
ORDER BY salary ASC
drop table #salary
The output is here 200 as 300 is first highest, 200 is second highest and 100 is the third highest as shown below
salary
200
Here n is 2

Query:
CREATE TABLE a
([Id] int, [Salary] int)
;
INSERT INTO a
([Id], [Salary])
VALUES
(1, 100),
(2, 200),
(3, 300)
;
GO
SELECT Salary as SecondHighestSalary
FROM a
ORDER BY Salary
OFFSET 1 ROWS FETCH NEXT 1 ROWS ONLY
| SecondHighestSalary |
| ------------------: |
| 200 |

select case
when cnt>1 then SecondHighestSalary
else null end as SecondHighestSalary
from
(select top 1 Salary as SecondHighestSalary,
(select count(distinct Salary) from Employee) as cnt
from (
select distinct top 2 Salary
from Employee
order by Salary desc ) as sal
order by SecondHighestSalary asc) as b

Select salary from employees limit 1,1 ;
Very easy way to find second highest salary

select
case when max(salary) is null then null else max(salary) end SecondHighestSalary
from (
select salary , dense_rank() over (order by salary desc) as rn
from Employee
)r
where rn = 2
This code returns null when there is no second highest salary

You can use the union condition to handle the null case
SELECT Salary as "SecondHighestSalary" from Employee
WHERE Salary < (SELECT MAX(salary) FROM Employee )
UNION
(SELECT null)
ORDER BY 1 DESC
LIMIT 1;

You can use exists() together with If-else statements.
Query:
If exists(select distinct salary as SecondHighestSalary from employee
order by salary desc offset 1 row fetch first 1 row only)
select distinct salary as SecondHighestSalary from employee
order by salary desc offset 1 row fetch first 1 row only
else select null as SecondHighestSalary;

#Please check the below code#
SELECT TOP 1 secondhighestsalary
FROM (SELECT
CASE WHEN z.SalaryRank >1 THEN Salary
ELSE null END secondhighestsalary, SalaryRank
FROM
(SELECT salary, RANK() OVER(ORDER BY Salary DESC) As SalaryRank
FROM Employee GROUP BY salary )z
GROUP BY Salary, SalaryRank
)c
ORDER BY secondhighestsalary DESC
Explanation:
** SELECT salary, RANK() OVER(ORDER BY Salary DESC) As SalaryRank
FROM Employee GROUP BY salary**
above query is to provide rank to Salary column, group by clause will take care the duplicate values ..... next
**SELECT
CASE WHEN z.SalaryRank >1 THEN Salary
ELSE null END secondhighestsalary, SalaryRank
FROM
(SELECT salary, RANK() OVER(ORDER BY Salary DESC) As SalaryRank
FROM Employee GROUP BY salary )z **
next piece of code assign NULL against rank 1 and salary for greater than 1 rank.
So if you have only one row in the table and as per our question we need to display second highest salary if not display NULL, it will take care that situation.
At last we need to Order by DESC and take the Top 1 record.

SELECT max(Salary) as SecondHighestSalary from Employee where salary <>(SELECT max(salary) from Employee)

Related

To find the Nth Highest Salary

Write a SQL query to get the nth highest salary from the Employee table (SQL Server)
| Id | Salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
For this example, the nth highest salary where n = 2 is 200. If there is no nth highest salary, then the query should return null.
| getNthHighestSalary(2) |
+------------------------+
| 200 |
Is there any way to write this query other than by using function?
Another possible approach is using ROW_NUMBER() or DENSE_RANK() functions. It is important to know if there can be more then one salary at or before Nth position.
CREATE TABLE #Salary (
[id] int,
[salary] numeric(10, 2)
)
INSERT #Salary
([id], [salary])
VALUES
(1, 100),
(2, 500),
(3, 200),
(4, 300),
(5, 200);
DECLARE #Position int = 2;
-- With possible duplicate salaries
WITH cte AS (
SELECT
[id], [salary],
DENSE_RANK() OVER (ORDER BY [salary] ASC) AS [DRPosition]
FROM #Salary
)
SELECT [id]
FROM cte
WHERE [DRPosition] = #Position
ORDER BY [DRPosition];
-- Without possible duplicate salaries
WITH cte AS (
SELECT
[id], [salary],
ROW_NUMBER() OVER (ORDER BY [salary] ASC) AS [RPosition]
FROM #Salary
)
SELECT [id]
FROM cte
WHERE [RPosition] = #Position
ORDER BY [RPosition]
The following does almost exactly what you want:
select salary
from employee
order by salary desc
offset <n> rows fetch next 1 row only;
The only problem is that it does not return NULL when there is no such salary. You can handle using a subquery:
select (select salary
from employee
order by salary desc
offset <n> rows fetch next 1 row only
) as salary;
If you want ties to have the same ranking, then use select distinct salary in the subquery.
You can try this for getting n-th highest salary, where n = 1,2,3....(int)
SELECT TOP 1 salary FROM (
SELECT TOP n salary
FROM employees
ORDER BY salary DESC) AS emp
ORDER BY salary ASC
Hope this will help you. Below is one of the implementation.
create table #salary (salary int)
insert into #salary values (100), (200), (300), (400), (500)
SELECT TOP 1 salary FROM (
SELECT TOP 3 salary
FROM #salary
ORDER BY salary DESC) AS emp
ORDER BY salary ASC
drop table #salary
The output is here 300 as 500 is first highest, 400 is second highest and 300 is the third highest as shown below
salary
300
Here n is 3
177. Nth Highest Salary - Leetcode
Try this out ! It worked !
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
SET N = N-1;
RETURN (
SELECT DISTINCT Salary as "getNthHighestSalary(2)"
FROM Employee
ORDER BY Salary DESC
LIMIT 1 OFFSET N
);
END
You can try this using row_number()
WITH CTE AS
(
SELECT EmpID, Salary,
RN = ROW_NUMBER() OVER (ORDER BY Salary DESC)
FROM Employee
)
SELECT EmpID, Salary
FROM CTE
WHERE RN = n
Finds the salary for which there exist exactly 8 higher salaries,
meaning finds the 9th highest salary.
Returns NULL if there is no 9th Salary:
SELECT DISTINCT e.Salary FROM Employee e WHERE
(SELECT COUNT(*) FROM Employee ie WHERE ie.Salary > e.Salary) = 8
UNION
SELECT NULL WHERE (SELECT COUNT(Salary) FROM Employee) < 9
You can simply try this using correlated sub-query to find Nth highest salary in Employee table..
SELECT *
FROM Employee Emp1
WHERE (N-1) = (
SELECT COUNT(DISTINCT(Emp2.Salary))
FROM Employee Emp2
WHERE Emp2.Salary > Emp1.Salary)
I tried this query and it worked
select sal from (select sal from employee
order by sal desc
limit n)
order by sal asc
limit 1
SELECT DISTINCT(Salary) FROM Employee ORDER BY Salary DESC LIMIT n-1,1;
The best approach
select salary from emp as e1
where N-1 (select count(distinct salary) from emp as e2
where e2.salary > e1.salary);
Another Possible approach.I think this could help .
select min(T.Salary) from
(
select distinct top n Salary from Employee order by Salary desc
)T

How to find third or nᵗʰ maximum salary from salary table?

How to find third or nth maximum salary from salary table(EmpID, EmpName, EmpSalary) in optimized way?
Row Number :
SELECT Salary,EmpName
FROM
(
SELECT Salary,EmpName,ROW_NUMBER() OVER(ORDER BY Salary) As RowNum
FROM EMPLOYEE
) As A
WHERE A.RowNum IN (2,3)
Sub Query :
SELECT *
FROM Employee Emp1
WHERE (N-1) = (
SELECT COUNT(DISTINCT(Emp2.Salary))
FROM Employee Emp2
WHERE Emp2.Salary > Emp1.Salary
)
Top Keyword :
SELECT TOP 1 salary
FROM (
SELECT DISTINCT TOP n salary
FROM employee
ORDER BY salary DESC
) a
ORDER BY salary
Use ROW_NUMBER(if you want a single) or DENSE_RANK(for all related rows):
WITH CTE AS
(
SELECT EmpID, EmpName, EmpSalary,
RN = ROW_NUMBER() OVER (ORDER BY EmpSalary DESC)
FROM dbo.Salary
)
SELECT EmpID, EmpName, EmpSalary
FROM CTE
WHERE RN = #NthRow
Try this
SELECT TOP 1 salary FROM (
SELECT TOP 3 salary
FROM employees
ORDER BY salary DESC) AS emp
ORDER BY salary ASC
For 3 you can replace any value...
If you want optimize way means use TOP Keyword, So the nth max and min salaries query as follows but the queries look like a tricky as in reverse order by using aggregate function names:
N maximum salary:
SELECT MIN(EmpSalary)
FROM Salary
WHERE EmpSalary IN(SELECT TOP N EmpSalary FROM Salary ORDER BY EmpSalary DESC)
for Ex: 3 maximum salary:
SELECT MIN(EmpSalary)
FROM Salary
WHERE EmpSalary IN(SELECT TOP 3 EmpSalary FROM Salary ORDER BY EmpSalary DESC)
N minimum salary:
SELECT MAX(EmpSalary)
FROM Salary
WHERE EmpSalary IN(SELECT TOP N EmpSalary FROM Salary ORDER BY EmpSalary ASC)
for Ex: 3 minimum salary:
SELECT MAX(EmpSalary)
FROM Salary
WHERE EmpSalary IN(SELECT TOP 3 EmpSalary FROM Salary ORDER BY EmpSalary ASC)
Too simple if you use the sub query!
SELECT MIN(EmpSalary) from (
SELECT EmpSalary from Employee ORDER BY EmpSalary DESC LIMIT 3
);
You can here just change the nth value after the LIMIT constraint.
Here in this the Sub query Select EmpSalary from Employee Order by EmpSalary DESC Limit 3; would return the top 3 salaries of the Employees. Out of the result we will choose the Minimum salary using MIN command to get the 3rd TOP salary of the employee.
Replace N with your Max Number
SELECT *
FROM Employee Emp1
WHERE (N-1) = (
SELECT COUNT(DISTINCT(Emp2.Salary))
FROM Employee Emp2
WHERE Emp2.Salary > Emp1.Salary)
Explanation
The query above can be quite confusing if you have not seen anything like it before – the inner query is what’s called a correlated sub-query because the inner query (the subquery) uses a value from the outer query (in this case the Emp1 table) in it’s WHERE clause.
And Source
Third or nth maximum salary from salary table without using subquery
select salary from salary
ORDER BY salary DESC
OFFSET N-1 ROWS
FETCH NEXT 1 ROWS ONLY
For 3rd highest salary put 2 in place of N-1
SELECT Salary,EmpName
FROM
(
SELECT Salary,EmpName,DENSE_RANK() OVER(ORDER BY Salary DESC) Rno from EMPLOYEE
) tbl
WHERE Rno=3
SELECT EmpSalary
FROM salary_table
GROUP BY EmpSalary
ORDER BY EmpSalary DESC LIMIT n-1, 1;
Refer following query for getting nth highest salary. By this way you get nth highest salary in MYSQL. If you want get nth lowest salary only you need to replace DESC by ASC in the query.
Method 1:
SELECT TOP 1 salary FROM (
SELECT TOP 3 salary
FROM employees
ORDER BY salary DESC) AS emp
ORDER BY salary ASC
Method 2:
Select EmpName,salary from
(
select EmpName,salary ,Row_Number() over(order by salary desc) as rowid
from EmpTbl)
as a where rowid=3
In 2008 we can use ROW_NUMBER() OVER (ORDER BY EmpSalary DESC) to get a rank without ties that we can use.
For example we can get the 8th highest this way, or change #N to something else or use it as a parameter in a function if you like.
DECLARE #N INT = 8;
WITH rankedSalaries AS
(
SELECT
EmpID
,EmpName
,EmpSalary,
,RN = ROW_NUMBER() OVER (ORDER BY EmpSalary DESC)
FROM salary
)
SELECT
EmpID
,EmpName
,EmpSalary
FROM rankedSalaries
WHERE RN = #N;
In SQL Server 2012 as you might know this is performed more intuitively using LAG().
Answering this question from the point of view of SQL Server as this is posted in the SQL Server section.
There many approaches of getting Nth salary and we can classify these approaches in two sections one using ANSI SQL approach and other using TSQL approach. You can also check out this find nth highest salary youtube video which shows things practically. Let’s try to cover three ways of writing this SQL.
Approach number 1: - ANSI SQL: - Using Simple order by and top keyword.
Approach number 2: - ANSI SQL: - Using Co-related subqueries.
Approach number 3: - TSQL: - using Fetch Next
Approach number 1: - Using simple order by and top.
In this approach we will using combination of order by and top keyword. We can divide our thinking process in to 4 steps: -
Step 1: - Descending :- Whatever data we have first make it descending by using order by clause.
Step 2:- Then use TOP keyword and select TOP N. Where N stands for which highest salary rank you want.
Step 3: - Ascending: - Make the data ascending.
Step 4:- Select top 1 .There you are done.
So, if you put down the above 4 logical steps in SQL it comes up something as shown below.
Below is the text of SQL in case you want to execute and test the same.
select top 1 * from (select top 2 EmployeeSalary from tblEmployee
order by EmployeeSalary desc) as innerquery order by EmployeeSalary
asc
Parameterization issue of Approach number 1
One of the biggest issues of Approach number 1 is “PARAMETERIZATION”.
If you want to wrap up the above SQL in to a stored procedure and give input which top salary you want as a parameter, it would be difficult by Approach number 1.
One of the things you can do with Approach number 1 is make it a dynamic SQL but that would not be an elegant solution. Let’s check out Approach number 2 which is an ANSI SQL approach.
Approach number 2: - Using Co-related subqueries.
Below is how co-related subquery solution will look like. In case you are new to Co-related subquery. Co-related subquery is a query which a query inside query. The outer query first evaluates, sends the record to the inner query, inner query then evaluates and sends it to the outer query.
“3” in the query is the top salary we want to find out.
Select E1.EmployeeSalary from tblEmployee as E1 where 3=(Select
count(*) from tblEmployee as E2 Where
E2.EmployeeSalary>=E1.EmployeeSalary)
So in the above query we have an outer query:-
Select E1.EmployeeSalary from tblEmployee as E1
and inner query is in the where clause. Watch those BOLD’s which indicate how the outer table alias is referred in the where clause which makes co-related evaluate inner and outer query to and fro: -
where 3=(Select count(*) from tblEmployee as E2 Where
E2.EmployeeSalary>=E1.EmployeeSalary)
So now let’s say you have records like 3000, 4000 ,1000 and 100 so below will be the steps: -
First 3000 will be send to the inner query.
Inner query will now check how many record values are greater than or equal to 3000. If the number of record counts is not equal, it will take next value which is 4000. Now for 3000 there are only 2 values which is greater than or equal, 3000 and 4000. So, Is number record count 2>-=3? .NO, so it takes second value which is 4000.
Again for 4000 how many record values are greater than or equal. If the number of record count is not equal, it will take next value which is 1000.
Now 1000 has 3 records more or equal than 1000, (3000,4000 and 1000 himself). This is where co-related stops and exits and gives the final output.
Approach number 3: - TSQL fetch and Next.
Third approach is by using TSQL. By using Fetch and Next, we can get the Nth highest easily.
But please do note, TSQL code will not work for other databases we will need to rewrite the whole code again.
It would be a three-step process:-
Step 1 Distinct and Order by descending: - First apply distinct and order by which made the salaries descending as well as weed off the duplicates.
Step 2 Use Offset: - Use TSQL Offset and get the top N-1 rows. Where N is the highest salary we want to get. Offset takes the number of rows specified, leaving the other rows. Why (N-1) because it starts from zero.
Step 3 Use Fetch: - Use fetch and get the first row. That row has the highest salary.
The SQL looks something as shown below.
Performance comparison
Below is the SQL plan for performance comparison.
Below is the plan for top and order by.
Below is the plan for co-related queries. You can see the number of operators are quiet high in numbers. So surely co-related would perform bad for huge data.
Below is TSQL query plan which is better than cor-related.
So, summing up we can compare more holistically as given in the below table.
declare #maxNthSal as nvarchar(20)
SELECT TOP 3 #maxNthSal=GRN_NAME FROM GRN_HDR ORDER BY GRN_NAME DESC
print #maxNthSal
To get third highest value from table
SELECT * FROM tableName ORDER BY columnName DESC LIMIT 2, 1
This is one of the popular question in any SQL interview. I am going to write down different queries to find out the nth highest value of a column.
I have created a table named “Emloyee” by running the below script.
CREATE TABLE Employee([Eid] [float] NULL,[Ename] [nvarchar](255) NULL,[Basic_Sal] [float] NULL)
Now I am going to insert 8 rows into this table by running below insert statement.
insert into Employee values(1,'Neeraj',45000)
insert into Employee values(2,'Ankit',5000)
insert into Employee values(3,'Akshay',6000)
insert into Employee values(4,'Ramesh',7600)
insert into Employee values(5,'Vikas',4000)
insert into Employee values(7,'Neha',8500)
insert into Employee values(8,'Shivika',4500)
insert into Employee values(9,'Tarun',9500)
Now we will find out 3rd highest Basic_sal from the above table using different queries.
I have run the below query in management studio and below is the result.
select * from Employee order by Basic_Sal desc
We can see in the above image that 3rd highest Basic Salary would be 8500. I am writing 3 different ways of doing the same. By running all three mentioned below queries we will get same result i.e. 8500.
First Way: - Using row number function
select Ename,Basic_sal
from(
select Ename,Basic_Sal,ROW_NUMBER() over (order by Basic_Sal desc) as rowid from Employee
)A
where rowid=2
Select TOP 1 Salary as '3rd Highest Salary' from (SELECT DISTINCT TOP 3 Salary from Employee ORDER BY Salary DESC) a ORDER BY Salary ASC;
I am showing 3rd highest salary
SELECT MIN(COLUMN_NAME)
FROM (
SELECT DISTINCT TOP 3 COLUMN_NAME
FROM TABLE_NAME
ORDER BY
COLUMN_NAME DESC
) AS 'COLUMN_NAME'
--nth highest salary
select *
from (select lstName, salary, row_number() over( order by salary desc) as rn
from employee) tmp
where rn = 2
--(nth -1) highest salary
select *
from employee e1
where 1 = (select count(distinct salary)
from employee e2
where e2.Salary > e1.Salary )
Optimized way: Instead of subquery just use limit.
select distinct salary from employee order by salary desc limit nth, 1;
See limit syntax here http://www.mysqltutorial.org/mysql-limit.aspx
By subquery:
SELECT salary from
(SELECT rownum ID, EmpSalary salary from
(SELECT DISTINCT EmpSalary from salary_table order by EmpSalary DESC)
where ID = nth)
Try this Query
SELECT DISTINCT salary
FROM emp E WHERE
&no =(SELECT COUNT(DISTINCT salary)
FROM emp WHERE E.salary <= salary)
Put n= which value you want
set #n = $n
SELECT a.* FROM ( select a.* , #rn = #rn+1 from EMPLOYEE order by a.EmpSalary desc ) As a where rn = #n
MySQL tested solution, assume N = 4:
select min(CustomerID) from (SELECT distinct CustomerID FROM Customers order by CustomerID desc LIMIT 4) as A;
Another example:
select min(country) from (SELECT distinct country FROM Customers order by country desc limit 3);
Try this code :-
SELECT *
FROM one one1
WHERE ( n ) = ( SELECT COUNT( one2.salary )
FROM one one2
WHERE one2.salary >= one1.salary
)
Find Nth highest salary from a table. Here is a way to do this task using dense_rank() function.
select linkorder from u_links
select max(linkorder) from u_links
select max(linkorder) from u_links where linkorder < (select max(linkorder) from u_links)
select top 1 linkorder
from ( select distinct top 2 linkorder from u_links order by linkorder desc) tmp
order by linkorder asc
DENSE_RANK :
1. DENSE_RANK computes the rank of a row in an ordered group of rows and returns the rank as a NUMBER. The ranks are consecutive integers beginning with 1.
2. This function accepts arguments as any numeric data type and returns NUMBER.
3. As an analytic function, DENSE_RANK computes the rank of each row returned from a query with respect to the other rows, based on the values of the value_exprs in the order_by_clause.
4. In the above query the rank is returned based on sal of the employee table. In case of tie, it assigns equal rank to all the rows.
WITH result AS (
SELECT linkorder ,DENSE_RANK() OVER ( ORDER BY linkorder DESC ) AS DanseRank
FROM u_links )
SELECT TOP 1 linkorder FROM result WHERE DanseRank = 5
In SQL Server 2012+, OFFSET...FETCH would be an efficient way to achieve this:
DECLARE #N AS INT;
SET #N = 3;
SELECT
EmpSalary
FROM
dbo.Salary
ORDER BY
EmpSalary DESC
OFFSET (#N-1) ROWS
FETCH NEXT 1 ROWS ONLY
select * from employee order by salary desc;
+------+------+------+-----------+
| id | name | age | salary |
+------+------+------+-----------+
| 5 | AJ | 20 | 100000.00 |
| 4 | Ajay | 25 | 80000.00 |
| 2 | ASM | 28 | 50000.00 |
| 3 | AM | 22 | 50000.00 |
| 1 | AJ | 24 | 30000.00 |
| 6 | Riu | 20 | 20000.00 |
+------+------+------+-----------+
select distinct salary from employee e1 where (n) = (select count( distinct(salary) ) from employee e2 where e1.salary<=e2.salary);
Replace n with the nth highest salary as number.
SELECT TOP 1 salary FROM ( SELECT TOP n salary FROM employees ORDER BY salary DESC Group By salary ) AS emp ORDER BY salary ASC
(where n for nth maximum salary)
Just change the inner query value: E.g Select Top (2)* from Student_Info order by ClassID desc
Use for both problem:
Select Top (1)* from
(
Select Top (1)* from Student_Info order by ClassID desc
) as wsdwe
order by ClassID

SQL command for finding the second highest salary

HI,
Can u tell me the syntax of the SQL command which gives as output the second highest salary from a range of salaries stored in the employee table.
A description of the SQL commnd will be welcomed...
Please help!!!
select min(salary) from
(select top 2 salary from SalariesTable order by salary desc)
as ax
This should work:
select * from (
select t.*, dense_rank() over (order by salary desc) rnk from employee t
) a
where rnk = 2;
This returns the second highest salary.
dense_rank() over is a window function, and it gives you the rank of a specific row within the specified set. It is standard SQL, as defined in SQL:2003.
Window functions are awesome in general, they simplyfy lots of difficult queries.
Slightly different solution:
This is identical except that returns the highest salary when there is a tie for number 1:
select * from (
select t.*, row_number() over (order by salary desc) rnk from employee t
) a
where rnk = 2;
Updated: Changed rank to dense_rank and added second solution. Thanks, IanC!
with tempTable as(
select top 2 max(salary) as MaxSalary from employee order by salary desc
) select top 1 MaxSalary from tempTable
description:
select the top 2 maximum salaries
order them by desc order ( so the 2nd highest salary is now at the top)
select the top 1 from that
another approach:
select top 1 MaxSalary from (
select top 2 max(salary) as MaxSalary from employee order by salary desc
)
Here's some sample code, with proof of concept:
declare #t table (
Salary int
)
insert into #t values (100)
insert into #t values (900)
insert into #t values (900)
insert into #t values (400)
insert into #t values (300)
insert into #t values (200)
;WITH tbl AS (
select t.Salary, DENSE_RANK() OVER (order by t.Salary DESC) AS Rnk
from #t AS t
)
SELECT *
FROM tbl
WHERE Rnk = 2
DENSE_RANK is mandatory (change to RANK & you'll see).
You'll also see why any SELECT TOP 2 queries won't work (without a DISTINCT anyway).
You don't specify the actual SQL product you're using, and the query language varies among products. However, something like this should get you started:
SELECT salary FROM employees E1
WHERE 1 = (SELECT COUNT(*) FROM employee E2 WHERE E2.salary > E1.salary)
(thanks to fredt for the correction).
Alternatively (and faster in terms of performance) would be
SELECT TOP 2 salary FROM employees ORDER BY salary DESC
and then skipping the first returned row.
An alternative (tested):
select Min(Salary) from (
select distinct TOP (2) salary from employees order by salary DESC) AS T
This will work on any platform, is clean, and caters for the possibility of multiple tied #1 salaries.
Select top 1 * from employee where empID in (select top 2 (empID) from employee order by salary DESC) ORDER BY salary ASC
Explanation:
select top 2 (empID) from employee order by salary DESC would give the two records for which Salary is top and then the whole query would sort it these two records in ASCENDING order and then list out the one with the lowest salary among the two.
EX. let the salaries of employees be 100, 99, 98,,50.
Query 1 would return the emp ID of the persons with sal 100 and 99
Whole query would return all data related to the person having salary 99.
SELECT Salary,EmpName
FROM
(
SELECT Salary,EmpName,ROW_NUMBER() OVER(ORDER BY Salary) As Rank
FROM EMPLOYEE
) A
WHERE A.Rank=n;
where n is the number of highest salary u r requesting the table.
Ucan also use DenseRank() function in place of ROW_NUMBER().
Thanks,
Suresh
An easier way..
select MAX(salary) as SecondMax from test where salary !=(select MAX(salary) from test)

How to fetch the nth highest salary from a table without using TOP and sub-query?

Recently in an interview I was asked to write a query where I had to fetch nth highest salary from a table without using TOP and any sub-query ?
I got totally confused as the only way I knew to implement it uses both TOP and sub-query.
Kindly provide its solution.
Thanks in advance.
Try a CTE - Common Table Expression:
WITH Salaries AS
(
SELECT
SalaryAmount, ROW_NUMBER() OVER(ORDER BY SalaryAmount DESC) AS 'RowNum'
FROM
dbo.SalaryTable
)
SELECT
SalaryAmount
FROM
Salaries
WHERE
RowNum <= 5
This gets the top 5 salaries in descending order - you can play with the RowNumn value and basically retrieve any slice from the list of salaries.
There are other ranking functions available in SQL Server that can be used, too - e.g. there's NTILE which will split your results into n groups of equal size (as closely as possible), so you could e.g. create 10 groups like this:
WITH Salaries AS
(
SELECT
SalaryAmount, NTILE(10) OVER(ORDER BY SalaryAmount DESC) AS 'NTile'
FROM
dbo.SalaryTable
)
SELECT
SalaryAmount
FROM
Salaries
WHERE
NTile = 1
This will split your salaries into 10 groups of equal size - and the one with NTile=1 is the "TOP 10%" group of salaries.
;with cte as(
Select salary,
row_number() over (order by salary desc) as rn
from salaries
)
select salary
from cte
where rn=#n
(or use dense_rank in place of row_number if you want the nth highest distinct salary amount)
Select *
From Employee E1
Where
N = (Select Count(Distinct(E2.Salary)) From Employee E2 Where E2.Salary >= E1.Salary)
with cte as(
select VendorId,IncomeDay,IncomeAmount,
Row_Number() over ( order by IncomeAmount desc) as RowNumber
from DailyIncome
)
select * from cte
where RowNumber=2
Display 5th Min Sal Emp Table.
SELECT * FROM (SELECT Dense_Rank () Over (ORDER BY Sal ASC) AS Rnk, Emp.* FROM Emp) WHERE
Rnk=5;
Try this.
SELECT * FROM
(SELECT Salary,
rownum AS roworder
FROM (select distinct Salary from employer)
ORDER BY Salary
)
where roworder = 6
;
It can simply be done as following for second highest-
Select MAX(Salary) from employer where Salary NOT IN(Select MAX(Salary) from employer);
But for Nth highest we have to use CTE(Common Table Expression).
try this. It may very easy to find nth rank items by using CTE
**
with result AS
(
SELECT *,dense_rank() over( order by Salary) as ranks FROM Employee
)
select *from RESULT Where ranks = 2
**
To find the Nth highest salary :
Table name - Emp
emplyee_id salary
1 2000
2 3000
3 5000
4 8000
5 7000
6 2000
7 1000
sql query -> here N is higest salary to be found :
select salary from (select salary from Emp order by salary DESC LIMIT N) AS E order by ASC LIMIT 1;
If there are duplicate entries of
30,000,
23,000,
23,000,
15,000,
14,800
then above selected query will not return correct output.
find correct query as below:
with salaries as
(
select Salary,DENSE_RANK() over (order by salary desc) as 'Dense'
from Table_1
)
select distinct salary from salaries
where dense=3
SELECT salery,name
FROM employ
ORDER BY salery DESC limit 1, OFFSET n
with CTE_name (salary,name)
AS
( row_num() over (order by desc salary) as num from tablename )
select salary, name from CTE_name where num =1;
This will work in oracle
In order to find the Nth highest salary, we are only considering unique salaries.Highest salary means no salary is higher than it, Second highest means only one salary is higher than it, 3rd highest means two salaries are higher than it,similarly,Nth highest salary means N-1 salaries are higher than it.
Well, you can do by using LIMIT keyword, which provides pagination
capability.You can do like below:
SELECT salary FROM Employee ORDER BY salary DESC LIMIT N-1, 1
Ex: 2nd highest salary in MySQL without subquery:
SELECT salary FROM Employee ORDER BY salary DESC LIMIT 1,1
6- ways to write Second Highest salary..**
1.select * from employee order by Salary desc offset 1 rows fetch next 1 row only
2.select max(salary) from Employee where salary<(select max(salary) from Employee)
3.select MAX(Salary) from Employee WHERE Salary NOT IN (select MAX(Salary) from Employee );
4.select max(e1.salary) from Employee e1,Employee e2 where e1.salary
5.with cte as(
SELECT *, ROW_NUMBER() OVER( order by SALARY desc) AS ROWNUM FROM EMPLOYEE as rn)
select *From cte where ROWNUM=2
6.select max(e1.Salary) from Employee e1,Employee e2 where e1.Salary
Correct way to get nth Highest salary using NTILE function.
SELECT DISTINCT SAL INTO #TEMP_A FROM EMPLOYEE
DECLARE #CNT INT
SELECT #CNT=COUNT(1) FROM #TEMP_A
;WITH RES
AS(
SELECT SAL,NTILE(#CNT) OVER (ORDER BY SAL DESC) NTL
FROM #TEMP_A )
SELECT SALFROM RES WHERE NTL=3
DROP TABLE #TEMP_A
salary ---> table name
SELECT salary
FROM salary S1
WHERE 5-1 = (
SELECT COUNT( DISTINCT ( S2.salary ) )
FROM salary S2
WHERE S2.salary > S1.salary );
Highest sal using ms sql server:
select sal from emp where sal=(select max(sal) from emp)
Second highest sal:
select max(sal) from emp where sal not in (select max(sal) from emp)
What if we are required to find Nth highest salary without Row_Number,Rank, Dense Rank and Sub Query?
Hope this below Query Helps out.
select * from [dbo].[Test] order by salary desc
Emp_Id Name Salary Department
4 Neelu 10000 NULL
2 Rohit 4000 HR
3 Amit 3000 OPS
1 Rahul 2000 IT
select B.Salary from TEst B join Test A
on B.Salary<=A.Salary
group by (B.Salary)
having count(B.salary)=2
Result:- 4000, The 2nd Highest.

How to find fifth highest salary in a single query in SQL Server

How to find fifth highest salary in a single query in SQL Server
In SQL Server 2005 & 2008, create a ranked subselect query, then add a where clause where the rank = 5.
select
*
from
(
Select
SalesOrderID, CustomerID, Row_Number() Over (Order By SalesOrderID) as RunningCount
From
Sales.SalesOrderHeader
Where
SalesOrderID > 10000
Order By
SalesOrderID
) ranked
where
RunningCount = 5
These work in SQL Server 2000
DECLARE #result int
SELECT TOP 5 #result = Salary FROM Employees ORDER BY Salary DESC
Syntax should be close. I can't test it at the moment.
Or you could go with a subquery:
SELECT MIN(Salary) FROM (
SELECT TOP 5 Salary FROM Employees ORDER BY Salary DESC
) AS TopFive
Again, not positive if the syntax is exactly right, but the approach works.
SELECT TOP 1 salary
FROM (
SELECT DISTINCT TOP n salary
FROM employee
ORDER BY salary DESC) a
ORDER BY salary
where n > 1 -- (n is always greater than one)
You can find any number of highest salary using this query.
To find the 5th higest salary from a database, the query is..
select MIN(esal) from (
select top 5 esal from tbemp order by esal desc) as sal
its working check it out
SELECT MIN(Salary) FROM (
SELECT TOP 2 Salary FROM empa ORDER BY Salary DESC
) AS TopFive
It's working correctly, please use it.
Can be Most easily solved by:
SELECT MIN(Salary) FROM (
SELECT Salary FROM empa ORDER BY Salary DESC limit 5
)TopFive
You can try some thing like :
select salary
from Employees a
where 5=(select count(distinct salary)
from Employees b
where a.salary > b.salary)
order by salary desc
The below query to gets the Highest salary after particular Employee name.
Just have a look into that!
SELECT TOP 1 salary FROM (
SELECT DISTINCT min(salary) salary
FROM emp where salary > (select salary from emp where empname = 'John Hell')
) a
ORDER BY salary
select * from employee2 e
where 2=(select count(distinct salary) from employee2
where e.salary<=salary)
its working
You can find it by using this query:
select top 1 salary
from (select top 5 salary
from tbl_Employee
order by salary desc) as tbl
order by salary asc