In Oracle SQL, use the ANSI FETCH FIRST n ROWS ONLY clause (introduced in Oracle 12c) after ORDER BY to limit rows cleanly. For older Oracle versions (11g and earlier), wrap the ordered SELECT in a subquery and filter by ROWNUM on the outer query—never put ROWNUM directly in the same query block as ORDER BY unless you want rows limited before sorting.
1. Oracle 12c and Later: ORDER BY ... FETCH FIRST n ROWS ONLY
Oracle applies ORDER BY before FETCH FIRST, making this the clearest and most standard way to fetch top-N or bottom-N rows.
SELECT
employee_id,
first_name,
salary
FROM employees
ORDER BY salary DESC, employee_id ASC
FETCH FIRST 5 ROWS ONLY;
FETCH FIRST 5 ROWS ONLYreturns the top 5 rows after sorting.- Include a tie-breaker column in
ORDER BY(such asemployee_id ASC) so results stay deterministic when values tie.
Including Ties (WITH TIES) or Percentages (PERCENT)
-- Include extra rows if salary ties at the 5th rank
SELECT
employee_id,
first_name,
salary
FROM employees
ORDER BY salary DESC
FETCH FIRST 5 ROWS WITH TIES;
-- Fetch the top 10% of rows
SELECT
employee_id,
first_name,
salary
FROM employees
ORDER BY salary DESC
FETCH FIRST 10 PERCENT ROWS ONLY;
2. Pagination with OFFSET ... FETCH NEXT (Oracle 12c+)
To skip rows and return the next page of sorted results, pair OFFSET with FETCH NEXT:
SELECT
employee_id,
first_name,
salary
FROM employees
ORDER BY salary DESC, employee_id ASC
OFFSET 10 ROWS
FETCH NEXT 5 ROWS ONLY;
OFFSET 10 ROWSskips the first 10 sorted rows.FETCH NEXT 5 ROWS ONLYreturns rows 11 through 15.
3. Oracle 11g and Earlier: Subquery + ROWNUM
In Oracle SQL, ROWNUM is assigned before ORDER BY is evaluated in the same query block. To sort first and then limit rows on older Oracle versions, use a subquery:
SELECT *
FROM (
SELECT
employee_id,
first_name,
salary
FROM employees
ORDER BY salary DESC, employee_id ASC
)
WHERE ROWNUM <= 5;
- The inner query sorts the rows first; the outer query limits the sorted result to the first 5 rows.
- Note:
WHERE ROWNUM > 5directly does not work becauseROWNUMstarts at 1 and increments only when a row is accepted; useROW_NUMBER()analytic function for range pagination on older Oracle versions.
Key Rules to Remember
- Use
ORDER BY ... FETCH FIRST n ROWS ONLYon Oracle 12c+ for readable top-N queries and pagination. - Always sort in a subquery before applying
WHERE ROWNUM <= nwhen supporting pre-12c Oracle databases. - Add deterministic tie-breakers to
ORDER BYwhenever duplicate sort keys exist.
You must log in or register to comment.
