Optimized query to find third and nth highest value or salary from given table in SQL

Table name : demotable 

select * from demotable

3rd maximum value:

SELECT TOP 1 value FROM (
   SELECT DISTINCT TOP 3 value
   FROM demotable
   ORDER BY value DESC) AS val
ORDER BY value ASC

OR 

SELECT MAX(value)
FROM demotable
WHERE value IN(SELECT DISTINCT TOP 3 value FROM demotable ORDER BY value ASC)

 

To get Nth highest value from above table

Nth maximum salary:

SELECT MAX(value)
FROM demotable
WHERE value IN(SELECT TOP N value FROM demotable ORDER BY valueASC)
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s