开发者

fetching data using rownum in oracle

I h开发者_开发百科ave 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 where rownum<5

is this is a wrong query to fetch data whose row number is less than 5.

when i used query like :

select * from table-name where rownum<=4

than it will gives a result record.

My question is what is wrong here with ?

Is this is syntax error or anything else??..


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:


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 ?


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜