How do I limit the number of rows returned by an Oracle query after ordering?
To limit the number of rows returned by an Oracle query after ordering, use the ROWNUM
pseudocolumn as follows:
Replace your_columns
, your_table
, your_order_column
with your specific columns, table, and order column, and max_rows
with the number of rows you want to fetch.
Limiting Rows: Oracle 12c onwards
From Oracle version 12c, Oracle introduced the OFFSET
and FETCH
clauses. This is a more straightforward way to limit output rows:
It's like telling the software, "Jump x
rows, then give me y
rows". It's perfect for pagination.
Dealing with duplicate values
Sometimes, you might end up with rows having the same values for the column you're ordering by. The FETCH
clause has the WITH TIES
option to deal with this:
Going by Percentages
Oracle 12c also allows you to fetch a top percentage of rows:
For versions older than Oracle 12c
Before Oracle 12c, life wasn't as easy. You'd have to leverage hierarchical queries. Here's how you can do it with ROWNUM
:
Using analytic functions
The ROW_NUMBER()
analytic function assigns unique row numbers according to sorting:
It's a touch more sophisticated, but it gives you great control over the rows you're fetching.
Mimicking OFFSET
By combining ROWNUM
with subqueries, you can create a pseudo OFFSET
:
Be mindful of large data sets
For big data sets, consider:
- Using cursor-based pagination with
OFFSET
andFETCH
. - Prefetching rows and storing keys in a temp table for faster access.
- Avoiding complex joins and subqueries that could slow down paginated results.
Choose the appropriate method for your needs
Your specific scenario determines the best approach:
- For precise row access, use
ROWNUM
with an inner subquery. - For pagination,
OFFSET
andFETCH
are your friends in Oracle 12c onwards. - If tied results need to be included as well, go for
FETCH FIRST ... WITH TIES
.
Was this article helpful?