in

code for eternity !!!

community website for .net freaks ;-)

Technology

T-SQL Query to Find the Second Lowest Column Value in a Table

After reading my earlier post T-SQL Query to Find the Second Highest Column Value in a Table a lot of users asked me to also help them with writing a query to find the second lowest column value in a table. So here it is: If we had a table named Employee which had a column named Salary and we had to find the second lowest Salary in the Employee table, the query for the same would be:

SELECT TOP 1 Salary FROM (SELECT TOP 2 Salary FROM Employee ORDER BY Salary ASC) AS E ORDER BY Salary DESC

If we ran the above query against the Employee table which had the following 5 rows:

5000
4000
3000
2000
1000

The subquery or the inner query would return the top 2 rows in ascending Salary order which would be:

1000
2000

The outer query would then select the top 1 row from the subquery results in descending Salary order which would be:

2000

Note that if we had to get the fourth lowest Salary, we could do so by simply changing the subquery from TOP 2 to TOP 4

Cheers,
Raj

~~~ CODING FOR ETERNITY !!! ~~~

Published Apr 30 2008, 09:41 AM by raj
Filed under:

I would really appreciate votes / kicks for this blog post if you found it useful ;-)

  kick it on DotNetKicks.com     Receive Email Updates


Comments

 

Dipti said:

Thanks a lot!!!!....really appreciate your reply..

Query for first five highest amount?

April 30, 2008 2:29 AM
 

DotNetKicks.com said:

You've been kicked (a good thing) - Trackback from DotNetKicks.com

April 30, 2008 1:38 PM

Leave a Comment

(required)  
(optional)
(required)  
Add


StopGlobalWarming.org  
Powered by Community Server (Non-Commercial Edition), by Telligent Systems