Quantcast
Channel: How do I limit the number of rows returned by an Oracle query after ordering? - Stack Overflow
Viewing all articles
Browse latest Browse all 17

Answer by Bartek for How do I limit the number of rows returned by an Oracle query after ordering?

$
0
0

Pagination queries with ordering are really tricky in Oracle.

Oracle provides a ROWNUM pseudocolumn that returns a number indicating the order in which the database selects the row from a table or set of joined views.

ROWNUM is a pseudocolumn that gets many people into trouble. A ROWNUM value is not permanently assigned to a row (this is a common misunderstanding). It may be confusing when a ROWNUM value is actually assigned. A ROWNUM value is assigned to a row after it passes filter predicates of the query but before query aggregation or sorting.

What is more, a ROWNUM value is incremented only after it is assigned.

This is why the followin query returns no rows:

 select *  from (select *       from some_table       order by some_column) where ROWNUM <= 4 and ROWNUM > 1; 

The first row of the query result does not pass ROWNUM > 1 predicate, so ROWNUM does not increment to 2. For this reason, no ROWNUM value gets greater than 1, consequently, the query returns no rows.

Correctly defined query should look like this:

select *from (select *, ROWNUM rnum      from (select *            from skijump_results            order by points)      where ROWNUM <= 4)where rnum > 1; 

Find out more about pagination queries in my articles on Vertabelo blog:


Viewing all articles
Browse latest Browse all 17

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>