Thursday, 23 June 2011

Query to find any Highest no.

Here i write a simple query to find any highest no from a list ..

for example--
Table_name---EMP

ename     salary
1            10,000
2             2000
3            5000
4            6000
5            7000

if u want to find 2nd highest salary from  emp table then...
-------------------------------------------------------------------
select min(sal)
           from ( select sal from emp order by sal desc)

  where rownum<=:2;
----------------------------------------------------------------------
output will show lyk this
SAL
7000.
----------------------------------------------------------------------
Detail explanation--

1)..1st u can sort the all record in descending order
at this stage SAL  look lyk this
10000
7000
6000
5000
2000

2) then u get th "highest" salary at 1st row,,,2nd hieghest at 2nd row, 3rdhieghest at 3rd row,onwords...

3)then select only 2nd row ...coz it disply 2nd hieghest salary....



IF U WANT TO FIND 3RD HIEGHEST SALARY THEN INSTEAD OF ROWNUM:=2 U CAN PUT ROWNUM:=3 IN QUERY ......

But Problem will occure If there are same value in two rows..

EX-
 salary
10000
7000
7000

5000
2000
 in above table2nd and 3rd column contain same value...
and if u need to show both row
then u can use following query-----
-------------------------------------------------------------------------- 
select sal
    from emp
    where sal=(
                       select min(sal)
                            from ( select sal from emp order by sal desc)
                               where rownum<=:2
                     );

-----------------------------------------------------------------------------------------------





hi frndz i hop this query will help u if any one ask u to find any heighest salary......

this is comman question asked for fresher during technical interview.....





2 comments:

  1. thanks. .
    are you going to post only about Oracle?

    ReplyDelete
  2. Sir i want to get the last number of a primary column from my table.
    can i use this query:-

    select min(sal)
    from ( select sal from emp order by sal desc)
    where rownum<=:1;
    please help.

    ReplyDelete