tags:

views:

134

answers:

3

i want to know the n'th highest value from a column of a table for eg: 2nd highest salary from tbl_salary or 4th highest salary from tbl_salary

i seen somewhere below query

select salary from tbl_salary t
where &n = (select count(salary) 
from (select distinct salary from tbl_salary)
where t.salary<=salary);

if this is correct then please tell me how it works?

or is there any other simple way to get result?

A: 

You can do it using the limit clause:

select * from tbl_salary order by salary desc limit 2,1;
hkda150
isn't this is oracle only?
nickf
yes you're right, thanks. Just changed my answer.
hkda150
A: 

I'm sure there is a better way to do this, but:

SELECT salary FROM tbl_salary ORDER BY salary DESC LIMIT n,1

Where n is the position you want - 1 (i.e. to get the second highest salary it would be LIMIT 1,1)

jasonbar
by using keyword `DISTINCT` will give accurate answer...m i right?
diEcho
@I Like PHP: If your table contains duplicate salaries, yes. Or you could use GROUP BY salary
jasonbar
+2  A: 

If it's a basic query, then just use LIMIT:

-- get the 4th highest salary
SELECT salary FROM tbl_salary
ORDER BY salary DESC
LIMIT 4,1
nickf
and if if it is not basic query then?
diEcho
well if it's not a derived field or anything (eg: I want to find the user record of the person who has posted the 5th most articles) this method will work fine. After that, it's probably just a case of using a subquery.
nickf