Replace Employee with your table name, and Salary with your column name. Where N is the level of Salary to be determined.
SELECT *
FROM Employee E1
WHERE (N-1) = (
SELECT COUNT(DISTINCT(E2.Salary))
FROM Employee E2
WHERE E2.Salary > E1.Salary)
In the above example, the inner query uses a value of the outer query in its filter condition meaning; the inner query cannot be evaluated before evaluating the outer query. So each row in the outer query is evaluated first and the inner query is run for that row.
Reference : Pinal Dave (http://blog.SQLAuthority.com)












It should be noted that for SQL Server 2005, using the row_number ranking function is a better, meaning easier to maintain, and more performant.
Hi,
This is the very nice query
Regards,
Manoj Kumar Singh
Wonderful. Thanks. keep on writing.
You are true genius.
Hi,
Thanks for the query.
Regards
Manohar K Patidar
Hi
This is a very good query
Keep it up
regards
Yogesh D Nayak
I got the correct solution from your website. thank u.
Regards,
Durga Prasad A.
Hi,
thanks for the best query.
Best regards…
kishor
Hello,
I want to find first 10 rows with max value from a table. Can you suggest me what should be query for this ?
Thanking you in advance.
Regds,
Bhavesh
Select Top 10 distinct Name,Vlaue from Table1 order by Value desc
Your examples are very useful in my job
Dear Sir/Madam,
Thanks for the perfect solution to find out the Nth record from sql server database.
Hi,
Tanks for the perfect n easy solution.
Thanks n Regards,
Manjusha
Tks for u r solution
how to get top 3 departments and bottom 3 departments
Hi,
Thanks for the perfect solution to find out the Nth record from sql server database.
One request:
how to get top 3 departments and bottom 3 departments
waiting for ur reply
with reagards
sekar
Top 3
Select top 3 * from table order by dept desc
Bottom 3
Select top 3 * from table order by dept asc
But you need to define what you meant by Top and bottom
hi
i want a query .dynamicale i new row should Added and it should display in Gui by using a Query.pleas provide me this query.
Regards
Srinath
[...] 8, 2008 by pinaldave I have previously written SQL SERVER – Query to Retrieve the Nth Maximum value. I just received email that if I can write this using AdventureWorks database as it is default [...]
[...] Please read my article here to find Nth Highest Salary of Employee table : SQL SERVER – Query to Retrieve the Nth Maximum value [...]
Hi executing the same query using Top keyword is much faster, when the number of records are comparatively too large. FYI (copied from the same site :) )
SELECT TOP 1 salary
FROM (
SELECT DISTINCT TOP 6 salary
FROM employee
ORDER BY salary DESC) a
ORDER BY salary
I want to find first 10 rows with max value from a table.
and
how to get top 3 departments and bottom 3 departments
Can you suggest me what should be queries for above two questions?
Thanks
krishna
Hi All,
I compared above said query and found this one performming like a Lamborghini Reventon as compared to the above proposed Ambassador, for table(id,name,salary) with 20K records:
DECLARE @myNth INT
SET @myNth=56
SELECT TOP 1 SALARY
FROM(
SELECT TOP(@myNth) SALARY
FROM MinMaxTable
ORDER BY Salary DESC
) T
ORDER BY Salary ASC
So This one is the BEST !!!!
Yeah.. I agree with your approach..
Hello sir,
i have one dpubt……..
How will we identify the duplicate key by refer the number?
Your query is correct if it came from student who has 5 minutes to solve this problem.
But if it in real world application,
Your query is very low performance.
Then try methods 4 and 5 specified in this link
http://beyondrelational.com/blogs/madhivanan/archive/2007/08/27/find-nth-maximum-value.aspx
Hi
following query will find out the nth max salary from employee table. just replace the number 5 with your number. Also it should check the duplicate value in salary field. I think Bala wants to know this.
SELECT max(salary) FROM ( SELECT DISTINCT TOP 5 salary FROM employee order by salary) a
Regards
Satyabrata Paul
Hi,
Can we find out the first inserted row from a table?
Regards
Manohar K Patidar Jamner (M. P. )
There is no concept of first/last row until you define it
table_a table_b
salary salary
_____ _____
1000 2000
3000 4000
I want a T-sql query to get “4000″ as answer
select max(salary) as salary from
(
select salary from table_a
union all
select salary from table_b
) as t
Hello Pinal Dave!!!
I am not able to understand why the following query gave me the correct answer
“SELECT *
FROM Employee E1
WHERE (N-1) = (
SELECT COUNT(DISTINCT(E2.Salary))
FROM Employee E2
WHERE E2.Salary > E1.Salary)”
Can you explain me in step by step manner how it returned correct answer?
I will be extremely thankful to you if you can do it for me.
Refer method 3
http://beyondrelational.com/blogs/madhivanan/archive/2007/08/27/find-nth-maximum-value.aspx
It is equalent to this method
The idea is to generate serial no based on the value and compare it in the where clause
in that where clause, u should specify the column name only. Not a variable
Thanks a lot! This query works well.
How to import by query, as I have below command for table import
exp rtrs_fd/rtrs_fd@reuters file=exp.dmp log=exp.log tables=
issue_counterparty_100 consistent=y
statistics=none buffer=10000000
imp REUT_ONSHORE/REUT_ONSHORE@REUT_US_105 file=C:\IMP\exp.dmp
log=C:\IMP\exp.log tables= issue_source_18_mar09 ignore=y commit=y
buffer=10000000
hi !! Pinal Dave,
Thanks for the query.. it is really helpful….
but can u explain in steps that how the above query actually works ?
becoz i dont know the execution flow of this query…
hi !! Pinal Dave,
Thanks for the query.. it is really helpful….
but can u explain in steps that how the above query actually works ?
becoz i dont know the execution flow of this query
There are N number of methods that includes aggregation, row_number(), top etc to get Nth Maximum value
Refer this to know more
http://beyondrelational.com/blogs/madhivanan/archive/2007/08/27/find-nth-maximum-value.aspx
i use sql 2008 and this query gives error .the error shows “Invalid column name ‘N’.” what is error pls tell me
hi biswajit,
here N stands for level means which salary level u want to get.
like n=1,2,3,4,5,6……………n,
try it
bye
You should relplace N with a specific value
If you use 5, it means 5th maximum
Hi,
I want to get top 5 salary from employee table without using sql function top and min or max.
Thanks
Why do you want to do this?
The following link has some methods that dont use TOP, min or max
Refer this
http://beyondrelational.com/blogs/madhivanan/archive/2007/08/27/find-nth-maximum-value.aspx
Hi Saurabh,
You can use ROWCOUNT property to fetch only five records from query.
SET ROWCOUNT 5;
select * from Employees
ORDER BY Salary DESC
Here I specify ROWCOUNT property to 5, so it will select only 5 records based on query.
By this way you can get top 5 employees having high salary.
Thanks,
Tejas
SQLYoga.com
Note that ROWCOUNT will not be supported (for INSERT, UPDATE and DELETE) in future release of the SQL Server. You should use TOP
hi pinal,
This is dhirendra!
i am quite satisfied by your query.
can u pls breifly give the steps how the query is executed.
waiting 4 ur reply.
thanks
It basically generate serial number based on the salary
It is generated in ascending order of the salary and you use use it in where clause to get Nth maximum value
Thanks for your query.
Regards,
Sambit
Hello Pinal Dave,
It works for me.Thanks.
Regards,
Minakshi.
Hi,
I am looking to retrieve similar data but in a different way but cant quite get it right.
What i have is a customer table and a Purchases table, and i want to create a view that will give me:
Customer, MostRecenetPurchase, SecondMostRecentPurchase,…
Please help!
Many Thanks
Scott
Hi, can you write a query to find the 5th Highest salary of a table without using inner / sub query.?
Thanks, Kishan
Make use of this post
http://beyondrelational.com/blogs/madhivanan/archive/2007/08/27/find-nth-maximum-value.aspx
Thankq sir
thanq sir
Thanks a lot,
I have a query, if I replace “N” with 1, then actually it return lowest and highest one salary.
SELECT *
FROM Employee E1
WHERE (1-1) = (
SELECT COUNT(DISTINCT(E2.Salary))
FROM Employee E2
WHERE E2.Salary > E1.Salary)
Why?
i want to find the second highest salary from table without ordering table and with no max or count function?
How can i do this???
please reply me…..
thank you..
from Kalpna Bindal
student of 3rd year in B.Tech.
select e.sal from emp e
where &n = (select count(distinct(b.sal)) from emp b
where e.sal <= b.sal);
very nice sir..makes a lot of help..thx.
Hi This query is working fine but whenever there is lacs of records in your table at that time it will take more time so as performance issue i think so my issue will work fine my solution is:
with result AS
(
select maths,RANK() over (order by maths desc) as row from tblResult group by maths
)
select * from result r inner join tblResult t on r.maths = t.Maths where ROW = 3
Here in this query write your table name instead of result , column name instead of maths and your number instead of 3
Thanks
Is this helpful? Please give reply.
Can somebody show me the execution row by row for the Nth max below:
CREATE TABLE Employee
(
EmpId int PRIMARY Key nonclustered,
Name VARCHAR(50),
MgrId int,
Salary int
);
sp_help employee
–drop table employee
INSERT INTO Employee
SELECT 1, ‘Mike’, 3, 100
UNION ALL
SELECT 2, ‘David’, 3, 200
UNION ALL
SELECT 3, ‘Roger’, NULL, 1000
UNION ALL
SELECT 4, ‘Marry’,2, 500
UNION ALL
SELECT 5, ‘Joseph’,2, 700
UNION ALL
SELECT 7, ‘Ben’,2, 50
GO
select * from Employee
order by salary desc
SELECT * FROM Employee E1
WHERE (5-1) = (
SELECT COUNT(DISTINCT(E2.Salary))
FROM Employee E2
WHERE E2.Salary > E1.Salary)
hi, i am getting time out error when i execute the following query
“select MAX(PartItemID) from PartItems”
my part item table having 6 lac records
is there any other way to get the max value for this table ..please help me if u know the solution
thank u
because it is taking too much time to execute it. when i execute it, it took 6 minutes and 3 seconds and your session expires that’s why it is giving time out error…..
[...] Query to Retrieve the Nth Maximum Value A very popular script on my blog. I am sure you have faced the similar situation in future. [...]
Hello sir,
your query took 6 minutes and 3 seconds to fetch 9th maximum value..