Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternatives to LIMIT and OFFSET for paging in Oracle [duplicate]

People also ask

What is the equivalent of limit in Oracle SQL?

Oracle Database does not have the LIMIT clause. However, since 12c release, it provided a similar but more flexible clause named row limiting clause. Similar to the statement that uses LIMIT clause above, the row limiting clause returns the top 5 products with the highest inventory level.

Why offset pagination is bad?

As we can see, OFFSET pagination has some drawbacks: For a high database volume, the end pages are harder to retrieve than the beginning pages, as the number of rows to load and skip is high. For a growing database, it becomes less and less efficient to reach the beginning rows over time.

Can I use offset without limit?

Basically, no. Limit must be supplied.

Does Oracle support limit and offset?

The row limiting clause is supported in Oracle queries starting with Oracle 12c R1 (12.1). Oracle does not use the LIMIT keyword; instead, it use the OFFSET and FETCH keywords. The query below will use offset and fetch to limit the number of rows returned.


As of oracle 12c, you could use the top N queries.

SELECT fieldA,fieldB 
FROM table 
ORDER BY fieldA 
OFFSET 5 ROWS FETCH NEXT 14 ROWS ONLY;

http://www.oracle-base.com/articles/12c/row-limiting-clause-for-top-n-queries-12cr1.php


Since you're on 10g, you should be able to simplify the ROWNUM approach using analytic functions

SELECT fieldA, 
       fieldB
  FROM (SELECT fieldA,
               fieldB,
               row_number() over (order by fieldA) rnk
          FROM table_name)
 WHERE rnk BETWEEN 5 AND 14;

You will need to use the rownum pseudocolumn to limit results. See here:

http://www.oracle.com/technology/oramag/oracle/06-sep/o56asktom.html

http://www.oracle.com/technetwork/issue-archive/2006/06-sep/o56asktom-086197.html


Method-1: For database version Oracle12c or higher

SELECT fieldA, fieldB 
FROM table 
ORDER BY fieldA 
OFFSET 5 ROWS FETCH NEXT 14 ROWS ONLY

Method-2: For database version Oracle11g or lower using analytical function RowNumber()

SELECT fieldA, fieldB
FROM (
    SELECT fieldA, fieldB,
        row_number() over (order by fieldA) rowRank
    FROM table_name
)
WHERE rowRank BETWEEN 5 AND 14;

Method-3: For database version Oracle11g or lower using RowNum

SELECT T.* FROM ( 
SELECT T.*, rowNum as rowIndex
FROM (
    SELECT fieldA, fieldB,
    FROM table_name
)T)T
WHERE rowIndex > 0 AND rowIndex <= 20;

In some cases, I have found method-3 is faster than method-2 since order by clause is mandatory in method 2. However, if your database version is 12c or higher you must go for method-1.