Search code examples
sqloracle-databaserownum

How to use rownum


I have a employee table in oracle with name,salary and other details.

I am trying to get the second highest salary but not able to fetch.

This one working fine

with e_salary as (select distinct salary from employee)
select salary from e_salary
order by salary desc

And gives output:

450000

61000

60000

50000

40000

30000

20000

6000

but when i am using the same query to fetch second highest row not getting any output

select salary
  from ( with e_salary as (select distinct salary from employee)
         select salary from e_salary order by salary desc)
 where rownum = 2

but as i replace the rownum=2 with rownum<2 it gives output of first two records. Please someone explain why rownum=2 is not working


Solution

  • This will work:

    select salary from ( select salary , rownum as rn from (select salary from e_salary order by salary desc)) where rn = 2;

    Why it doesn't work:

    When assigning ROWNUM to a row, Oracle starts at 1 and only only increments the value when a row is selected; that is, when all conditions in the WHERE clause are met. Since our condition requires that ROWNUM is greater than 2, no rows are selected and ROWNUM is never incremented beyond 1.

    Hope u are clear right now.