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 sampathsris for How do I limit the number of rows returned by an Oracle query after ordering?

$
0
0

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   sometableORDER BY nameOFFSET 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_testSELECT levelFROM   dualCONNECT BY level <= 10;COMMIT;

What's in the table?

SELECT valFROM   rownum_order_testORDER BY val;       VAL----------         1         1         2         2         3         3         4         4         5         5         6         6         7         7         8         8         9         9        10        1020 rows selected.

Get first N rows

SELECT valFROM   rownum_order_testORDER BY val DESCFETCH FIRST 5 ROWS ONLY;       VAL----------        10        10         9         9         85 rows selected.

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

SELECT valFROM   rownum_order_testORDER BY val DESCFETCH FIRST 5 ROWS WITH TIES;       VAL----------        10        10         9         9         8         86 rows selected.

Top x% of rows

SELECT valFROM   rownum_order_testORDER BY valFETCH FIRST 20 PERCENT ROWS ONLY;       VAL----------         1         1         2         24 rows selected.

Using an offset, very useful for pagination

SELECT valFROM   rownum_order_testORDER BY valOFFSET 4 ROWS FETCH NEXT 4 ROWS ONLY;       VAL----------         3         3         4         44 rows selected.

You can combine offset with percentages

SELECT valFROM   rownum_order_testORDER BY valOFFSET 4 ROWS FETCH NEXT 20 PERCENT ROWS ONLY;       VAL----------         3         3         4         44 rows selected.

Viewing all articles
Browse latest Browse all 17

Trending Articles



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