1123

Is there a way to make an Oracle query behave like it contains a MySQL limit clause?

In MySQL, I can do this:

select * 
from sometable
order by name
limit 20,10

to get the 21st to the 30th rows (skip the first 20, give the next 10). The rows are selected after the order by, so it really starts on the 20th name alphabetically.

In Oracle, the only thing people mention is the rownum pseudo-column, but it is evaluated before order by, which means this:

select * 
from sometable
where rownum <= 10
order by name

will return a random set of ten rows ordered by name, which is not usually what I want. It also doesn't allow for specifying an offset.

Mark Rotteveel
  • 82,132
  • 136
  • 114
  • 158
Mathieu Longtin
  • 13,574
  • 6
  • 24
  • 34
  • 19
    Standardized in SQL:2008. – dalle Jan 26 '09 at 14:18
  • 1
    Looks like the offset and row_count are reversed in your first MySQL example. That query will select rows 11 to 30, not 21 to 30. – volni Jun 21 '11 at 14:47
  • 15
    Limit was announced by Tom Kyte for Oracle 12c... – wolφi Dec 03 '12 at 11:44
  • Consider it offtopic but I can hardly imagine real life use-cases when you need to extract data from the middle of dataset. No kidding. Maybe I am just a lucky one that haven't come accross such requirements yet. If someone could give an example especially based on real experience... – Yaroslav Shabalin Dec 09 '13 at 21:43
  • 16
    Fetching the next page in a result set? – Mathieu Longtin Dec 16 '13 at 16:33
  • 4
    @YaroslavShabalin In particular, a paged search uses this pattern *all* the time. Almost any app with any kind of search function is going to use it. Another use case would be loading only part of a long list or table client side and giving the user the option to expand. – jpmc26 Aug 14 '14 at 19:19
  • 1
    @MathieuLongtin @jpmc26 In google do you initially begin from page number 10? Why need to execute query each time the next page is loaded when you can execute it once, open cursor and navigate by loading certain part of dataset? Yes you have to deal with memory management things if resultset is large, but avoid possible inconsistency. Consider that number of rows in resultset changes, each time you re-query with above `limit 20,10` you can get different result. – Yaroslav Shabalin Aug 15 '14 at 08:47
  • 3
    @YaroslavShabalin You can't get a different result set unless the underlying data changes because of the `ORDER BY`. That's the whole point of ordering first. If the underlying data changes and your result set changes because of it, then why not show the user the updated results instead of outdated information? Also, state management is a plague to be avoided as much as possible. It's a constant source of complication and bugs; that's why functional is getting so popular. And when would you know to expire the entire result set in memory? In web, you have no way of knowing when the user leaves. – jpmc26 Aug 15 '14 at 15:03
  • 1
    @jpmc26 OK, I get your point. Now it makes sense. – Yaroslav Shabalin Aug 16 '14 at 04:11
  • 3
    @YaroslavShabalin - opening a cursor and holding it open for an extended period of time in a multi-user scenario is a good way to tie a relational database in knots. In a single-user database this probably doesn't matter, but when you've got hundreds of simultaneous connections this is very likely to lead to problems. Relational databases are generally designed as transactional DB's with relatively short transaction durations. YMMV. Share and enjoy. – Bob Jarvis - Reinstate Monica Aug 17 '14 at 20:18
  • See [How pagination works in Oracle SQL](https://stackoverflow.com/questions/30321483/how-rownum-works-in-pagination-query/30321788#30321788) – Lalit Kumar B Jan 21 '18 at 14:13
  • See also [Paging with Oracle](https://stackoverflow.com/questions/241622/paging-with-oracle) – Vadzim Apr 24 '18 at 17:56

14 Answers14

815

You can use a subquery for this like

select *
from  
( select * 
  from emp 
  order by sal desc ) 
where ROWNUM <= 5;

Have also a look at the topic On ROWNUM and limiting results at Oracle/AskTom for more information.

Update: To limit the result with both lower and upper bounds things get a bit more bloated with

select * from 
( select a.*, ROWNUM rnum from 
  ( <your_query_goes_here, with order by> ) a 
  where ROWNUM <= :MAX_ROW_TO_FETCH )
where rnum  >= :MIN_ROW_TO_FETCH;

(Copied from specified AskTom-article)

Update 2: Starting with Oracle 12c (12.1) there is a syntax available to limit rows or start at offsets.

SELECT * 
FROM   sometable
ORDER BY name
OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY;

See this answer for more examples. Thanks to Krumia for the hint.

Kosi2801
  • 19,793
  • 12
  • 34
  • 41
  • 5
    This is definitely the way to do it, but be aware (as the ask tom article says) the query performance degrades as your max rownum increases. This is a good solution for query results where you only want to see the first few pages, but if you are using this as a mechanism for code to page through a whole table you would be better off refactoring your code – Chris Gill Aug 27 '09 at 12:30
  • 1
    +1 your lower/upper version actually helped me work around an issue where a mere upper-bounded rownum clause was drastically slowing down my query. – Kelvin Aug 09 '11 at 22:21
  • 1
    The Leigh Riffel "analytic solution with only one nested query" is the one. – Darren Hicks Mar 27 '12 at 23:22
  • 7
    The AskTom article has an optimizer hint as well that uses SELECT /*+ FIRST_ROWS(n) */ a.*, rownum rnum The closing slash should be preceded by an asterisk. SO is scrubbing it out. – David Mann Mar 05 '13 at 15:34
  • 1
    Note that for Oracle 11 an outer SELECT with ROWNUM will prevent you from calling deleteRow on an UpdatableResultSet (with ORA-01446) - looking forward to that 12c R1 change! – nsandersen May 11 '15 at 08:34
  • In the first query, doesn't the inner query have to retrieve all rows before the external one can filter out all but the first five? – Tulains Córdova Dec 02 '15 at 12:48
  • Unlike the FETCH NEXT n ROWS approach, the subquery with ROWNUM restriction is applicable together with the "FOR UPDATE" clause. – nrainer Apr 26 '20 at 09:07
  • The first query is also valuable because original set of columns is preserved. In environments where query result is subsequently processed by some ORM tool, it's necessary to get _n_ columns from table `t.*` rather than _n+1_ columns including some kind of renamed `rownum`. Nonstandard `select * except rnum` clause would solve this problem, however very few databases support it at this moment AFAIK. Also, the rownum-based solution easily works only to emulate `limit` clause. Emulating `offset` clause is harder because of timing of computing `rownum` (can be circumvented using reversed order). – Tomáš Záluský Jun 23 '20 at 07:02
730

Starting from Oracle 12c R1 (12.1), there is a row limiting clause. It does not use familiar LIMIT syntax, but it can do the job better with more options. You can find the full syntax here. (Also read more on how this works internally in Oracle in this answer).

To answer the original question, here's the query:

SELECT * 
FROM   sometable
ORDER BY name
OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY;

(For earlier Oracle versions, please refer to other answers in this question)


Examples:

Following examples were quoted from linked page, in the hope of preventing link rot.

Setup

CREATE TABLE rownum_order_test (
  val  NUMBER
);

INSERT ALL
  INTO rownum_order_test
SELECT level
FROM   dual
CONNECT BY level <= 10;

COMMIT;

What's in the table?

SELECT val
FROM   rownum_order_test
ORDER BY val;

       VAL
----------
         1
         1
         2
         2
         3
         3
         4
         4
         5
         5
         6
         6
         7
         7
         8
         8
         9
         9
        10
        10

20 rows selected.

Get first N rows

SELECT val
FROM   rownum_order_test
ORDER BY val DESC
FETCH FIRST 5 ROWS ONLY;

       VAL
----------
        10
        10
         9
         9
         8

5 rows selected.

Get first N rows, if Nth row has ties, get all the tied rows

SELECT val
FROM   rownum_order_test
ORDER BY val DESC
FETCH FIRST 5 ROWS WITH TIES;

       VAL
----------
        10
        10
         9
         9
         8
         8

6 rows selected.

Top x% of rows

SELECT val
FROM   rownum_order_test
ORDER BY val
FETCH FIRST 20 PERCENT ROWS ONLY;

       VAL
----------
         1
         1
         2
         2

4 rows selected.

Using an offset, very useful for pagination

SELECT val
FROM   rownum_order_test
ORDER BY val
OFFSET 4 ROWS FETCH NEXT 4 ROWS ONLY;

       VAL
----------
         3
         3
         4
         4

4 rows selected.

You can combine offset with percentages

SELECT val
FROM   rownum_order_test
ORDER BY val
OFFSET 4 ROWS FETCH NEXT 20 PERCENT ROWS ONLY;

       VAL
----------
         3
         3
         4
         4

4 rows selected.
Community
  • 1
  • 1
sampathsris
  • 19,015
  • 10
  • 59
  • 90
189

I did some performance testing for the following approaches:

Asktom

select * from (
  select a.*, ROWNUM rnum from (
    <select statement with order by clause>
  ) a where rownum <= MAX_ROW
) where rnum >= MIN_ROW

Analytical

select * from (
  <select statement with order by clause>
) where myrow between MIN_ROW and MAX_ROW

Short Alternative

select * from (
  select statement, rownum as RN with order by clause
) where a.rn >= MIN_ROW and a.rn <= MAX_ROW

Results

Table had 10 million records, sort was on an unindexed datetime row:

  • Explain plan showed same value for all three selects (323168)
  • But the winner is AskTom (with analytic following close behind)

Selecting first 10 rows took:

  • AskTom: 28-30 seconds
  • Analytical: 33-37 seconds
  • Short alternative: 110-140 seconds

Selecting rows between 100,000 and 100,010:

  • AskTom: 60 seconds
  • Analytical: 100 seconds

Selecting rows between 9,000,000 and 9,000,010:

  • AskTom: 130 seconds
  • Analytical: 150 seconds
giannis christofakis
  • 7,151
  • 4
  • 48
  • 63
zeldi
  • 4,663
  • 3
  • 17
  • 18
56

An analytic solution with only one nested query:

SELECT * FROM
(
   SELECT t.*, Row_Number() OVER (ORDER BY name) MyRow FROM sometable t
) 
WHERE MyRow BETWEEN 10 AND 20;

Rank() could be substituted for Row_Number() but might return more records than you are expecting if there are duplicate values for name.

sampathsris
  • 19,015
  • 10
  • 59
  • 90
Leigh Riffel
  • 5,897
  • 2
  • 30
  • 46
  • 3
    I love analytics. You might want to clarify what the difference in behavior would be between Rank() and Row_Number(). – Dave Costa Jan 23 '09 at 16:53
  • Indeed, not sure why I didn't think about duplicates. So, in this case if there are duplicate values for name then RANK could give more records than you are expecting therefore you should use Row_Number. – Leigh Riffel Jan 26 '09 at 14:11
  • If mentioning `rank()` it is also worth noting `dense_rank()` which may be more useful for output control as the latter does not "skip" numbers, whereas `rank()` can. In any case for this question `row_number()` is best suited. One other not is this technique is applicable to any db that supports the functions mentioned. – Paul Maxwell Oct 29 '17 at 00:34
29

On Oracle 12c (see row limiting clause in SQL reference):

SELECT * 
FROM sometable
ORDER BY name
OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY;
sampathsris
  • 19,015
  • 10
  • 59
  • 90
beldaz
  • 3,849
  • 3
  • 38
  • 58
  • 56
    And of course, they had to use a totally different syntax than everybody else so far – Mathieu Longtin Sep 25 '13 at 01:12
  • 9
    Clearly after sitting down with all the other vendors to agree on `LIMIT` in SQL:2008 they then had to take a leaf out of Microsoft's book and break the standard. – beldaz Sep 25 '13 at 01:39
  • 1
    Interestingly I heard recently that the most recent standard includes this syntax, so maybe Oracle pushed it in first before implementing. Arguably it is more flexible than `LIMIT ... OFFSET` – beldaz Dec 31 '13 at 23:08
  • 3
    @Derek: Yes, not following the standard is regrettable. But newly introduced functionality in 12cR1 is more powerful than just `LIMIT n, m` (See my answer). Then again, Oracle should have implemented `LIMIT n, m` as syntactic sugar, as it is equivalent to `OFFSET n ROWS FETCH NEXT m ROWS ONLY`. – sampathsris Sep 26 '14 at 13:54
  • 10
    @Derek: Actually, I just noticed this remark in the PostgreSQL manual http://www.postgresql.org/docs/9.0/static/sql-select.html#AEN69535 "The clauses LIMIT and OFFSET are PostgreSQL-specific syntax, also used by MySQL. The SQL:2008 standard has introduced the clauses OFFSET ... FETCH {FIRST|NEXT} ... for the same functionality". So LIMIT was never part of the standard. – beldaz May 21 '15 at 00:58
  • 1
    @beldaz I found your link broken (because of changed anchor?), proper is http://www.postgresql.org/docs/9.0/static/sql-select.html#AEN69605 (for now of course ;-)) – Wirone Oct 23 '15 at 11:51
  • 1
    @Wirone: For now: http://www.postgresql.org/docs/9.0/static/sql-select.html#SQL-LIMIT – sampathsris Mar 08 '16 at 04:06
  • 1
    @Krumia Thanks. Could even use www.postgresql.org/docs/current/static/sql-select.html#SQL-LIMIT for most recent version – beldaz Mar 08 '16 at 04:13
  • 1
    All standardization argument aside, if you just need something that works for Oracle, as of 2014 this is now the best of all the answers, IMHO. +1 – trpt4him May 16 '16 at 13:30
19

SQL Standard

Since version 12c Oracle supports the SQL:2008 Standard, which provides the following syntax to limit the SQL result set:

SELECT
    title
FROM
    post
ORDER BY
    id DESC
FETCH FIRST 50 ROWS ONLY

Oracle 11g and older versions

Prior to version 12c, to fetch the Top-N records, you had to use a derived table and the ROWNUM pseudocolumn:

SELECT *
FROM (
    SELECT
        title
    FROM
        post
    ORDER BY
        id DESC
)
WHERE ROWNUM <= 50
Vlad Mihalcea
  • 103,297
  • 39
  • 432
  • 788
15

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:

Bartek
  • 197
  • 1
  • 4
9

As an extension of accepted answer Oracle internally uses ROW_NUMBER/RANK functions. OFFSET FETCH syntax is a syntax sugar.

It could be observed by using DBMS_UTILITY.EXPAND_SQL_TEXT procedure:

Preparing sample:

CREATE TABLE rownum_order_test (
  val  NUMBER
);

INSERT ALL
  INTO rownum_order_test
SELECT level
FROM   dual
CONNECT BY level <= 10;
COMMIT;

Query:

SELECT val
FROM   rownum_order_test
ORDER BY val DESC
FETCH FIRST 5 ROWS ONLY;

is regular:

SELECT "A1"."VAL" "VAL" 
FROM  (SELECT "A2"."VAL" "VAL","A2"."VAL" "rowlimit_$_0",
               ROW_NUMBER() OVER ( ORDER BY "A2"."VAL" DESC ) "rowlimit_$$_rownumber" 
      FROM "ROWNUM_ORDER_TEST" "A2") "A1" 
WHERE "A1"."rowlimit_$$_rownumber"<=5 ORDER BY "A1"."rowlimit_$_0" DESC;

db<>fiddle demo

Fetching expanded SQL text:

declare
  x VARCHAR2(1000);
begin
 dbms_utility.expand_sql_text(
        input_sql_text => '
          SELECT val
          FROM   rownum_order_test
          ORDER BY val DESC
          FETCH FIRST 5 ROWS ONLY',
        output_sql_text => x);

  dbms_output.put_line(x);
end;
/

WITH TIES is expanded as RANK:

declare
  x VARCHAR2(1000);
begin
 dbms_utility.expand_sql_text(
        input_sql_text => '
          SELECT val
          FROM   rownum_order_test
          ORDER BY val DESC
          FETCH FIRST 5 ROWS WITH TIES',
        output_sql_text => x);

  dbms_output.put_line(x);
end;
/

SELECT "A1"."VAL" "VAL" 
FROM  (SELECT "A2"."VAL" "VAL","A2"."VAL" "rowlimit_$_0",
              RANK() OVER ( ORDER BY "A2"."VAL" DESC ) "rowlimit_$$_rank" 
       FROM "ROWNUM_ORDER_TEST" "A2") "A1" 
WHERE "A1"."rowlimit_$$_rank"<=5 ORDER BY "A1"."rowlimit_$_0" DESC

and offset:

declare
  x VARCHAR2(1000);
begin
 dbms_utility.expand_sql_text(
        input_sql_text => '
          SELECT val
FROM   rownum_order_test
ORDER BY val
OFFSET 4 ROWS FETCH NEXT 4 ROWS ONLY',
        output_sql_text => x);

  dbms_output.put_line(x);
end;
/


SELECT "A1"."VAL" "VAL" 
FROM  (SELECT "A2"."VAL" "VAL","A2"."VAL" "rowlimit_$_0",
             ROW_NUMBER() OVER ( ORDER BY "A2"."VAL") "rowlimit_$$_rownumber" 
       FROM "ROWNUM_ORDER_TEST" "A2") "A1" 
       WHERE "A1"."rowlimit_$$_rownumber"<=CASE  WHEN (4>=0) THEN FLOOR(TO_NUMBER(4)) 
             ELSE 0 END +4 AND "A1"."rowlimit_$$_rownumber">4 
ORDER BY "A1"."rowlimit_$_0"
Lukasz Szozda
  • 120,610
  • 18
  • 161
  • 197
5

Less SELECT statements. Also, less performance consuming. Credits to: anibal@upf.br

SELECT *
    FROM   (SELECT t.*,
                   rownum AS rn
            FROM   shhospede t) a
    WHERE  a.rn >= in_first
    AND    a.rn <= in_first;
  • 2
    Furthermore, it is totally incorrect answer. Question was about limiting AFTER the sorting. So rownum should be out of subquery. – BitLord Sep 18 '17 at 07:20
3

If you are not on Oracle 12C, you can use TOP N query like below.

SELECT *
 FROM
   ( SELECT rownum rnum
          , a.*
       FROM sometable a 
   ORDER BY name
   )
WHERE rnum BETWEEN 10 AND 20;

You can even move this from clause in with clause as follows

WITH b AS
( SELECT rownum rnum
      , a.* 
   FROM sometable a ORDER BY name
) 
SELECT * FROM b 
WHERE rnum BETWEEN 10 AND 20;

Here actually we are creating a inline view and renaming rownum as rnum. You can use rnum in main query as filter criteria.

sandi
  • 86
  • 4
  • 1
    In my case this didn't return the right rows. What I did to fix it is to do the `ORDER BY` and the `rownum` separately. [Basically I created a sub-query that had the `ORDER BY` clause](https://pastebin.com/M5dt4c00). – Patrick Gregorio May 10 '18 at 20:28
  • Downvote as it is incorrect answer. Question was about limiting after the sorting so `rownum` should be outside of a subquery. – Piotr Dobrogost Mar 13 '19 at 09:06
  • @PiotrDobrogost rownum is outside only. – sandi Sep 30 '19 at 08:49
2

I'v started preparing for Oracle 1z0-047 exam, validated against 12c While prepping for it i came across a 12c enhancement known as 'FETCH FIRST' It enables you to fetch rows /limit rows as per your convenience. Several options are available with it

- FETCH FIRST n ROWS ONLY
 - OFFSET n ROWS FETCH NEXT N1 ROWS ONLY // leave the n rows and display next N1 rows
 - n % rows via FETCH FIRST N PERCENT ROWS ONLY

Example:

Select * from XYZ a
order by a.pqr
FETCH FIRST 10 ROWS ONLY
arjun gaur
  • 458
  • 8
  • 22
  • 3
    http://stackoverflow.com/a/26051830/635608 - this has already been provided in other answers. Please refrain from posting stuff that's already been posted months ago. – Mat Jun 01 '16 at 11:43
  • 1
    oh sure,didn't go through every answer, i came across the subquery ones early on,will keep that in mind. – arjun gaur Jun 01 '16 at 12:48
1

For each row returned by a query, the ROWNUM pseudocolumn returns a number indicating the order in which Oracle selects the row from a table or set of joined rows. The first row selected has a ROWNUM of 1, the second has 2, and so on.

  SELECT * FROM sometable1 so
    WHERE so.id IN (
    SELECT so2.id from sometable2 so2
    WHERE ROWNUM <=5
    )
    AND ORDER BY so.somefield AND ROWNUM <= 100 

I have implemented this in oracle server 11.2.0.1.0

Sumesh TG
  • 2,367
  • 1
  • 12
  • 29
0
select * FROM (SELECT 
   ROW_NUMBER() OVER (ORDER BY sal desc),* AS ROWID, 
 FROM EMP ) EMP  where ROWID=5

greater then values find out

select * FROM (SELECT 
       ROW_NUMBER() OVER (ORDER BY sal desc),* AS ROWID, 
     FROM EMP ) EMP  where ROWID>5

less then values find out

select * FROM (SELECT 
       ROW_NUMBER() OVER (ORDER BY sal desc),* AS ROWID, 
     FROM EMP ) EMP  where ROWID=5
  • Downvote as `ROW_NUMBER()` based solution had already been posted by Leigh Riffel. In addiction there are syntax errors in code shown. – Piotr Dobrogost Mar 13 '19 at 08:33
-4

(untested) something like this may do the job

WITH
base AS
(
    select *                   -- get the table
    from sometable
    order by name              -- in the desired order
),
twenty AS
(
    select *                   -- get the first 30 rows
    from base
    where rownum < 30
    order by name              -- in the desired order
)
select *                       -- then get rows 21 .. 30
from twenty
where rownum > 20
order by name                  -- in the desired order

There is also the analytic function rank, that you can use to order by.

EvilTeach
  • 26,577
  • 21
  • 79
  • 136
  • 2
    This won't return a single row as the ROWNUM is a column on the resultset so that last WHERE condition will always be false. Plus you can't use ROWNUM and an ORDER BY an guarantee ORDER. – Ben Sep 08 '13 at 12:20
  • 2
    Excellent. Let's leave this here as a warning to others. – EvilTeach Jan 21 '14 at 15:33