Sub topic 11
Limiting Rows with FETCH FIRST
This chapter assumes you can write a SELECT with WHERE and ORDER BY, and that you have the HR sample schema available. The row limiting clause is how you ask Oracle for only the first few rows of a result. You use it for top-N reports, paging through results, and previews of large tables.
The syntax
The row limiting clause is the last part of a query. It is available from Oracle Database 12c.
SELECT employee_id, last_name, salary
FROM employees
ORDER BY salary DESC
OFFSET 0 ROWS
FETCH FIRST 5 ROWS ONLY;The general form is:
[ OFFSET n { ROW | ROWS } ]
[ FETCH { FIRST | NEXT } [ n | p PERCENT ] { ROW | ROWS } { ONLY | WITH TIES } ]Both parts are optional, and you can use either one alone.
FIRSTandNEXTare synonyms.ROWandROWSare synonyms. Choose the words that read naturally:FETCH FIRST 1 ROW ONLY,OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY.OFFSETskips rows before returning any.FETCHcaps how many rows come back, either as a count or as a percentage.ONLYstops exactly at the limit.WITH TIESmay return extra rows, as described below.
Where the clause sits in processing
Oracle applies the row limit after everything else. It filters with WHERE, builds the select list, removes duplicates with DISTINCT, and sorts with ORDER BY. Only then does it skip and cut rows.
This order explains most of the behavior in the rest of the chapter. The limit always applies to the sorted result, so the sort decides which rows count as "first".
Always pair it with ORDER BY
A table has no inherent row order. Without ORDER BY, FETCH FIRST 5 ROWS ONLY returns five rows, but Oracle may choose any five. The result can change after an index is added, after data is reloaded, or when a different execution plan is chosen.
-- Valid, but the five rows are arbitrary
SELECT employee_id, last_name
FROM employees
FETCH FIRST 5 ROWS ONLY;Oracle accepts this query without complaint. It is fine for a quick look at a table. Do not use it when the result matters.
Top-N queries
A top-N query sorts by some measure and keeps the best N rows.
SELECT employee_id, last_name, salary
FROM employees
ORDER BY salary DESC
FETCH FIRST 5 ROWS ONLY;Sort ascending to get the bottom N. Use WHERE to restrict the pool first.
SELECT employee_id, last_name, hire_date
FROM employees
WHERE department_id = 50
ORDER BY hire_date
FETCH FIRST 3 ROWS ONLY;This returns the three earliest hires in department 50. The filter runs before the limit, so you get three rows from department 50, not three rows overall.
If you omit the number, Oracle returns one row. FETCH FIRST ROW ONLY is a short form of FETCH FIRST 1 ROW ONLY.
Ties: ONLY versus WITH TIES
Suppose you want the two highest salaries, and two employees share the second-highest value. With ONLY, Oracle cuts at exactly two rows and the order between tied rows is arbitrary. Which of the tied employees you see is not guaranteed.
SELECT last_name, salary
FROM employees
ORDER BY salary DESC
FETCH FIRST 2 ROWS ONLY;WITH TIES also returns every further row whose ORDER BY values equal those of the last row in the limit.
SELECT last_name, salary
FROM employees
ORDER BY salary DESC
FETCH FIRST 2 ROWS WITH TIES;In the standard HR data, the top salary is 24000. Two employees share the next value, 17000. The query above therefore returns three rows: one at 24000 and both at 17000. The result can be larger than the number you asked for.
Two rules apply to WITH TIES:
- It requires
ORDER BY. Without a sort there is nothing to tie on, and Oracle raises an error. - Ties are judged only on the
ORDER BYcolumns. If you add a tiebreaker column to theORDER BY, such asemployee_id, rows rarely tie any more, andWITH TIESstops adding rows.
Percentages
Use PERCENT to take a share of the result set instead of a fixed count.
SELECT employee_id, last_name, salary
FROM employees
ORDER BY salary DESC
FETCH FIRST 5 PERCENT ROWS ONLY;With 107 rows in HR, 5 percent is 5.35 rows. Oracle rounds the row count up, so this returns 6 rows. Oracle must know the total number of rows before it can return any, so it has to produce the full sorted result first. This costs more than a fixed count. A percentage greater than 100 is treated as 100, and a negative percentage as 0.
Paging with OFFSET
OFFSET skips a number of rows, and FETCH NEXT then takes a page. Page numbering follows from simple arithmetic: for page p with page size s, the offset is (p - 1) * s.
-- Page 3, ten rows per page
SELECT employee_id, last_name, salary
FROM employees
ORDER BY salary DESC, employee_id
OFFSET 20 ROWS
FETCH NEXT 10 ROWS ONLY;Note the second sort key, employee_id. When rows tie on salary, their relative order is not guaranteed, and it could differ between two runs of the query. A row might then appear on two pages or on none. Finish every paging ORDER BY with a column that is unique, usually the primary key.
You can bind both values from your application:
SELECT employee_id, last_name, salary
FROM employees
ORDER BY salary DESC, employee_id
OFFSET :skip_rows ROWS
FETCH NEXT :page_size ROWS ONLY;Using bind variables lets Oracle reuse one parsed statement for every page, so you should prefer them to building the numbers into the SQL text.
Cost of deep pages
OFFSET does not jump to a position. Oracle still sorts and walks past all the skipped rows. Page 1 is cheap, and page 5000 costs roughly as much as reading 5000 pages. For deep paging on large tables, many applications switch to keyset pagination, where the next query filters by the last key seen:
SELECT employee_id, last_name, salary
FROM employees
WHERE employee_id > :last_seen_id
ORDER BY employee_id
FETCH FIRST 10 ROWS ONLY;An index on employee_id lets this start directly after the last row. The trade-off is that users can step forward and backward but cannot jump to an arbitrary page number.
Edge cases
| Situation | Result |
|---|---|
| `FETCH FIRST 0 ROWS ONLY` | No rows returned |
| Row count is negative or null | Treated as 0, so no rows |
| `OFFSET` larger than the number of rows | No rows returned |
| `OFFSET` negative or null | Treated as 0 |
| Fewer rows than the limit | All rows returned, with no error |
| `FETCH FIRST ROW ONLY` | One row |
One restriction matters in practice: you cannot combine the row limiting clause with FOR UPDATE. If you need to lock the top rows, find them in a subquery first and lock them in the outer query by key.
The pre-12c approach and its trap
Older code uses the ROWNUM pseudocolumn. You will meet it in existing applications, so it helps to know why the naive form is wrong.
-- Wrong for top-N: ROWNUM is assigned BEFORE ORDER BY runs
SELECT employee_id, last_name, salary
FROM employees
WHERE ROWNUM <= 5
ORDER BY salary DESC;Oracle assigns ROWNUM as rows come out of the filtering stage, before sorting. This query takes five arbitrary rows and then sorts them. The correct pattern sorts in an inline view first:
SELECT employee_id, last_name, salary
FROM (
SELECT employee_id, last_name, salary
FROM employees
ORDER BY salary DESC
)
WHERE ROWNUM <= 5;FETCH FIRST expresses the same intent in one flat statement and avoids this mistake. Use ROWNUM only when you must support releases before 12c.
Common mistakes
- Forgetting
ORDER BY, so the "first" rows are arbitrary. - Expecting
WITH TIESto return exactly N rows. - Paging with a non-unique sort key, which produces duplicated or missing rows between pages.
- Using
OFFSETfor very deep pages on large tables. - Writing
WHERE ROWNUM <= n ORDER BY ...and expecting a top-N result.
Exercise
Write a query on the HR employees table that returns the 3 most recently hired employees (columns employeeid, lastname, hire_date). Add a tiebreaker so the result is repeatable. Then explain what changes if you replace ONLY with WITH TIES and the tiebreaker column is removed from the ORDER BY.
Show answer
SELECT employeeid, lastname, hiredate FROM employees ORDER BY hiredate DESC, employeeid FETCH FIRST 3 ROWS ONLY; The query returns exactly three rows, and employeeid makes the order repeatable when hire dates match. With WITH TIES and ORDER BY hiredate DESC alone, Oracle returns the three newest rows plus any further rows whose hiredate equals that of the third row, so the result can contain more than three rows.
Exercise
A web page shows 25 employees per page, sorted by last_name. Write the query for page 4, and name the column you should add to the ORDER BY and why.
Show answer
SELECT employeeid, lastname FROM employees ORDER BY lastname, employeeid OFFSET 75 ROWS FETCH NEXT 25 ROWS ONLY; The offset is (4 - 1) * 25 = 75. employeeid is added because lastname is not unique, and without a unique final sort key, rows that share a last name may appear on two pages or on none.