11

Is there a command akin to:

  • 2nd highest salary from tbl_salary or

  • 4th highest salary from tbl_salary ?

I've seen:

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

How does this it works?

Are there other simple ways to get result?

Pacerier
  • 86,231
  • 106
  • 366
  • 634
xkeshav
  • 53,360
  • 44
  • 177
  • 245

8 Answers8

15

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 3,1
rekinyz
  • 6,576
  • 2
  • 29
  • 32
nickf
  • 537,072
  • 198
  • 649
  • 721
  • and if if it is not basic query then? – xkeshav Feb 24 '10 at 06:36
  • 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 Feb 24 '10 at 13:11
  • 3
    @nickf, I'm getting 5th highest by executing the above query! `limit 3,1` will get 4th highest, am I right? Please advise – arun May 04 '14 at 05:17
  • @arun, `limit 0,1` is first result. So yes `limit 3,1` is 4th. – Pacerier Apr 14 '15 at 07:44
8
select * from employee order by salary desc limit 1,1

Description : limit x,y

  • x: The row offset from which you want to start displaying records. For nth record it will be n-1.
  • y: The number of records you want to display. (Always 1 in this case)
Pradeep S
  • 165
  • 2
  • 10
6

// for highest salary of table

select salary from table order by salary desc limit 0,1

// for second highest salary

select salary from table order by salary desc limit 1,1

Using this query you get nth number of salary from table....

Wiseguy
  • 20,522
  • 8
  • 65
  • 81
4

Here is a very simple way to get the result of n'th highest value

put n=2 to get second highest salary
pur n=4 to get fourth highest salary
and so on...

Here is query
if n=2

select salary from tbl_salary e1
where 2 = (
select distinct(count(salary))
from tbl_salary e2
where e1.salary< e2.salary
)

Best luck

Swapnil T
  • 557
  • 7
  • 17
2

SELECT sal from emp order by sal desc limit 1,1

imran ansari
  • 685
  • 5
  • 2
2

You can do it using the limit clause:

select * from tbl_salary order by salary desc limit 2,1;
road242
  • 2,492
  • 22
  • 30
2

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
  • 13,333
  • 4
  • 38
  • 46
0

Simplest Implementation,

 (select * from tbl_salary order by salary desc limit 5) order by salary limit 1;


 (select * from tbl_salary order by salary desc limit 2) order by salary limit 1;
Shankar Thiyagaraajan
  • 1,705
  • 4
  • 28
  • 46