fetching data using rownum in oracle

前端 未结 3 1580
梦如初夏
梦如初夏 2021-01-23 11:04

I have a query in oracle to fetch data from table using rownum but i didn\'t get any data.
My query is like this :

select * from table-name wher

相关标签:
3条回答
  • 2021-01-23 11:25

    rownum is a pseudo column that counts rows in the result set after the where clause has been applied.

      SELECT table_name
        FROM user_tables
        WHERE rownum > 2;
    TABLE_NAME                     
    ------------------------------
    
    0 rows selected
    

    However, this query will always return zero rows, regardless of the number of rows in the table.

    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.

    http://blog.lishman.com/2008/03/rownum.html

    another stackoverflow link

    Edited

    this paragraph i find on oracle website which is much better

    Conditions testing for ROWNUM values greater than a positive integer are always false. For example, this query returns no rows:

    SELECT * FROM employees
        WHERE ROWNUM > 1;
    

    The first row fetched is assigned a ROWNUM of 1 and makes the condition false. The second row to be fetched is now the first row and is also assigned a ROWNUM of 1 and makes the condition false. All rows subsequently fail to satisfy the condition, so no rows are returned.

    You can also use ROWNUM to assign unique values to each row of a table, as in this example:

    0 讨论(0)
  • 2021-01-23 11:35

    Syntax seems correct to me.

    However ROWNUM is calculated on result rows for example:

    SELECT * FROM TABLE_NAME WHERE ROWNUM < 10 ORDER BY TABLE_FIELD ASC;
    

    and

    SELECT * FROM TABLE_NAME WHERE ROWNUM < 10 ORDER BY TABLE_FIELD DESC;
    

    Will give you different results.

    Each time a query is executed, for each tuple, Oracle assigns a ROWNUM which is scopet to that only query.

    What are you trying to accomplish ?

    0 讨论(0)
  • 2021-01-23 11:42

    Since for the reasons rahularyansharma mentions, rownum based queries won't always function the way you might expect, a way around this is to do something like

    SELECT * from (SELECT rownum AS rn, TABLE_NAME.* FROM TABLE_NAME)
    where rn > 5;
    

    However, be aware that this will be a fairly inefficient operation when operating over large datasets.

    0 讨论(0)
提交回复
热议问题