Selecting the second row of a table using rownum

后端 未结 9 1481
栀梦
栀梦 2020-11-28 14:07

I have tried the below query:

select empno from (
                   select empno 
                     from emp
                    order by sal desc
               


        
9条回答
  •  死守一世寂寞
    2020-11-28 14:51

    To explain this behaviour, we need to understand how Oracle processes ROWNUM. When assigning ROWNUM to a row, Oracle starts at 1 and 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.

    The bottom line is that conditions such as the following will work as expected.

    .. WHERE rownum = 1;

    .. WHERE rownum <= 10;

    While queries with these conditions will always return zero rows.

    .. WHERE rownum = 2;

    .. WHERE rownum > 10;

    Quoted from Understanding Oracle rownum

    You should modify you query in this way in order to work:

    select empno
    from
        (
        select empno, rownum as rn 
        from (
              select empno
              from emp
              order by sal desc
              )
        )
    where rn=2;
    

    EDIT: I've corrected the query to get the rownum after the order by sal desc

提交回复
热议问题