How do you limit rows returned by an Oracle SQL query after applying ORDER BY? | A1Lab@HumairaM to SQLEnglish • 2 days ago

How do you limit rows returned by an Oracle SQL query after applying ORDER BY?

message-square
0

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 ONLY returns the top 5 rows after sorting.
  • Include a tie-breaker column in ORDER BY (such as employee_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 ROWS skips the first 10 sorted rows.
  • FETCH NEXT 5 ROWS ONLY returns 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 > 5 directly does not work because ROWNUM starts at 1 and increments only when a row is accepted; use ROW_NUMBER() analytic function for range pagination on older Oracle versions.

Key Rules to Remember

  1. Use ORDER BY ... FETCH FIRST n ROWS ONLY on Oracle 12c+ for readable top-N queries and pagination.
  2. Always sort in a subquery before applying WHERE ROWNUM <= n when supporting pre-12c Oracle databases.
  3. Add deterministic tie-breakers to ORDER BY whenever duplicate sort keys exist.