Skip to main content

A SELECT cannot have a comparison with ROWNUM and an ORDER BY at the same level

ZPA rule for PL/SQL and Oracle SQL · SelectWithRownumAndOrderBy

In a query, the WHERE clause is applied before the ORDER BY. A condition on ROWNUM in the same query therefore keeps the first rows Oracle happens to read, and only those are sorted: WHERE ROWNUM <= 5 ORDER BY created_at DESC does not return the five newest rows.

This rule reports a comparison with ROWNUM in the WHERE clause of a query that has an ORDER BY. Sort in a subquery and filter on ROWNUM outside it, or use FETCH FIRST n ROWS ONLY.

Examples​

Noncompliant Code Example
select c.code, c.created_at
from crate c
where rownum <= 5 -- Noncompliant
order by c.created_at desc;
Compliant Solution
select c.code, c.created_at
from crate c
order by c.created_at desc
fetch first 5 rows only;