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 !!! ~~~