Limit an ordered Oracle query correctly
A top-N query must decide which rows come first before limiting their number. Applying ROWNUM in the same query block as a later ORDER BY can select an arbitrary subset and only then sort that subset.
Use the row-limiting clause for current Oracle code. Keep the nested ROWNUM pattern for maintenance work that must support an older database. Both examples below are read-only and build their own fixture from DUAL.
Define what the first two rows mean
The fixture has four readings with scores 40, 90, 70 and 70. The rule is descending score followed by ascending id. It therefore selects id 2 with score 90 and id 3 with score 70. The id is a deliberate tie-breaker between the two equal scores.
Run either alternative independently in an Oracle SQL client. The modern form works on Oracle 12c and later and is described here against the Oracle Database 19c SQL reference. The old form remains useful for understanding earlier code, without being the preferred new syntax.
Use FETCH FIRST
WITH Scores(Id, Person, Score) AS (
SELECT 1, 'Ada', 40 FROM dual
UNION ALL SELECT 2, 'Lin', 90 FROM dual
UNION ALL SELECT 3, 'Sam', 70 FROM dual
UNION ALL SELECT 4, 'Kai', 70 FROM dual
)
SELECT Id, Person, Score
FROM Scores
ORDER BY Score DESC, Id ASC
FETCH FIRST 2 ROWS ONLY;
The row-limiting clause follows the ordering. It returns up to two rows, so a source with only one qualifying row would return one. Without an ordering, the limit does not identify a stable business choice.
The selected rows are 2 / Lin / 90 and 3 / Sam / 70, in that order. No table creation or mutation is needed for the demonstration.
Maintain the nested ROWNUM form
WITH Scores(Id, Person, Score) AS (
SELECT 1, 'Ada', 40 FROM dual
UNION ALL SELECT 2, 'Lin', 90 FROM dual
UNION ALL SELECT 3, 'Sam', 70 FROM dual
UNION ALL SELECT 4, 'Kai', 70 FROM dual
)
SELECT Id, Person, Score
FROM (
SELECT Id, Person, Score
FROM Scores
ORDER BY Score DESC, Id ASC
)
WHERE ROWNUM <= 2
ORDER BY Score DESC, Id ASC;
The inner query orders the candidate rows before the outer query applies ROWNUM. The outer ordering also states the required display order. Moving ROWNUM <= 2 into the inner query would change that selection sequence.
A condition such as ROWNUM > 2 is not a direct pagination shortcut. Oracle's pseudocolumn is assigned as rows are selected, so that predicate does not simply skip the first two records.
Decide whether the boundary includes ties
ONLY caps this result at two rows. WITH TIES can include additional rows sharing the last selected ordering key. If the business wants everyone with one of the top two score positions, order by Score DESC alone and use FETCH FIRST 2 ROWS WITH TIES. Both score-70 rows then qualify, producing three rows in total.
Adding the unique id to that ordering removes the tie. When ties are defined by score but display order also needs an id, select the tied set in an inner query and order that set separately outside it. Do not unintentionally redefine tie equality while trying to stabilize presentation.
Plan pagination separately
OFFSET 2 ROWS FETCH NEXT 2 ROWS ONLY skips two rows in the ordered result. Use a unique total ordering, and decide how concurrent inserts or score changes should affect successive pages. Separate queries can observe changed data, so an offset is not a snapshot guarantee.
For deep pages, evaluate a keyset or continuation-key approach against the workload. The correct predicate must follow every component and direction of the ordering. This example demonstrates selection semantics, not a performance benchmark or a concurrent pagination implementation.
Source and further reading
This article addresses the problem raised by Mathieu Longtin in “How do I limit the number of rows returned by an Oracle query after ordering?” on Stack Overflow, licensed under CC BY-SA 4.0 . The question is the topic source. The explanations and examples here are newly authored from the database documentation, rather than reproduced from a community answer.
Author: Herman Schoenfeld