Scrivio Interview library
DebuggingFoundations6 min read · updated 12 November 2026

A developer writes SELECT * FROM orders WHERE ROWNUM <= 10 ORDER BY created_at DESC in Oracle to get the 10 newest orders, and the results are wrong. Explain why and give two correct versions.

ROWNUM is assigned to rows as Oracle fetches them, before the ORDER BY is applied, so the query takes 10 arbitrary rows and only then sorts those 10. The classic fix sorts in an inline view first: SELECT * FROM (SELECT * FROM orders ORDER BY created_at DESC) WHERE ROWNUM <= 10. On Oracle 12c and later the clearer fix is SELECT * FROM orders ORDER BY created_at DESC FETCH FIRST 10 ROWS ONLY.

Why this question is asked

Top-N queries are everywhere: the newest orders, the last ten logins, the first page of search results. On Oracle the old ROWNUM pseudocolumn makes it very easy to write one that looks right, returns ten plausible rows in testing, and is quietly wrong in production. Interviewers ask this because it checks whether we understand the order in which a query is evaluated, not just its syntax. In this answer, we will recap what ROWNUM is, see exactly why the query is wrong, write the two correct versions, look at the odd ROWNUM > 10 case, and see what Hibernate generates for us.

1A Quick Recap of ROWNUM

ROWNUM is a pseudocolumn, a value Oracle makes up for each row of a result rather than one stored in the table. It is a counter: the first row that passes the WHERE clause gets ROWNUM 1, the next gets 2, and so on. The important word is passes. The number is given at the moment a row is fetched and accepted, which is earlier than sorting.

2Why the Query Returns the Wrong Rows

A SELECT is evaluated in a logical order: Oracle reads rows from the table, applies WHERE, and only after that applies ORDER BY. Because ROWNUM is part of the WHERE clause, the limit is applied to rows in whatever order Oracle happens to read them, which is usually the physical order of the table or of an index it chose.

Java
-- Intended: the 10 newest orders
SELECT * FROM orders WHERE ROWNUM <= 10 ORDER BY created_at DESC;
-- What Oracle actually does:
-- read rows in storage order, give them ROWNUM 1, 2, 3 ...
-- stop after ROWNUM 10 -> 10 arbitrary orders, often old ones
-- sort those 10 by created_at -> they look correctly sorted, but they are the wrong 10
Step throughHow Oracle evaluates the broken query
  1. Read rows in storage orderno particular date order
  2. Give each row a ROWNUM1, 2, 3 as rows are accepted
  3. Stop at ROWNUM 1010 arbitrary orders
  4. Sort those 10 by created_at DESCsorted, but the wrong set

4 steps in order. Play them, or step through them one at a time.

This is why the bug survives testing. The ten rows come back nicely sorted, and on a small test table that was just loaded, the storage order may even match the insert order. In production, after deletes and space reuse, the first rows read can be from anywhere.

3Correct Version 1: Sort in an Inline View

The classic fix, which works on every Oracle version, is to sort first inside a subquery and apply ROWNUM outside it. The inner query produces all orders in the right order, and the outer query numbers them as they come out of that sorted set.

SQL
SELECT *
FROM (SELECT * FROM orders ORDER BY created_at DESC)
WHERE ROWNUM <= 10;
-- 10 newest orders

Notice that this does not have to sort the whole table. Oracle recognises the pattern and uses a top-N sort (shown as SORT ORDER BY STOPKEY in the plan) that keeps only the best 10 rows in memory, and with an index on created_at it can read just the first 10 index entries and stop.

4Correct Version 2: FETCH FIRST on Oracle 12c and Later

Oracle 12c added the SQL standard row-limiting clause. It is applied after ORDER BY, which is exactly what we meant in the first place.

SQL
SELECT * FROM orders
ORDER BY created_at DESC
FETCH FIRST 10 ROWS ONLY;
-- 10 newest orders
-- Second page of 10
SELECT * FROM orders
ORDER BY created_at DESC, id DESC
OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY;

In the paging example we added id as a tie breaker. If two orders share the same created_at, the database is free to return them in either order, and a row can then appear on two pages or on none. A unique last sort column makes the order deterministic. The same FETCH FIRST syntax works on PostgreSQL, and SQL Server 2012 and later accepts the OFFSET ... FETCH NEXT form (it requires the OFFSET part), which is useful when code must run on several engines.

5Why WHERE ROWNUM > 10 Returns Nothing

A developer who wants the second page might write WHERE ROWNUM > 10. It always returns zero rows. The first row fetched is a candidate for ROWNUM 1, and 1 > 10 is false, so it is rejected. The next row is then again a candidate for ROWNUM 1, because no row has been accepted yet, and it is rejected too. No row can ever reach 11.

For pagination with ROWNUM we therefore need two levels: number the sorted rows in a middle query and keep the alias, then filter on that alias outside.

SQL
SELECT * FROM (
SELECT o.*, ROWNUM rn
FROM (SELECT * FROM orders ORDER BY created_at DESC, id DESC) o
WHERE ROWNUM <= 20
)
WHERE rn > 10;
-- rows 11 to 20

6What Hibernate Generates

When we call setFirstResult and setMaxResults on a JPA query, we never write ROWNUM ourselves. Hibernate's Oracle dialect produces the limit SQL for the database version it detects: OFFSET and FETCH FIRST on 12c and later, and the nested ROWNUM wrapping on older versions. Recent Hibernate versions only support newer Oracle releases, so in practice we see FETCH FIRST, but check your version and look at the generated SQL in the logs if a page looks wrong.

Java
List<Order> newest = em.createQuery(
"select o from Order o order by o.createdAt desc, o.id desc", Order.class)
.setMaxResults(10)
.getResultList();
// Oracle 12c+: ... order by o1_0.created_at desc, o1_0.id desc fetch first ? rows only

7Follow-up questions

Could ROW_NUMBER() be used instead?

Yes. SELECT * FROM (SELECT o.*, ROW_NUMBER() OVER (ORDER BY created_at DESC) rn FROM orders o) WHERE rn <= 10 is correct, because the analytic function numbers rows after ordering them. It is also how we get the newest N per group, by adding PARTITION BY customer_id.

Is OFFSET paging a good idea for deep pages?

Not for deep pages. OFFSET 100000 still makes the database produce and discard 100,000 rows. For long lists, keyset pagination is better: remember the last created_at and id from the previous page and ask for rows WHERE (created_at, id) < (:last_created, :last_id) in the same order, which uses the index and costs the same for every page.

What does FETCH FIRST 10 ROWS WITH TIES do?

It returns the first 10 rows plus any further rows that tie with the 10th on the ORDER BY columns. If the 10th and 11th orders have exactly the same created_at, both are returned, so the result can have more than 10 rows.

8Conclusion

In this answer, we saw that ROWNUM is assigned as rows are fetched and accepted, before ORDER BY, so WHERE ROWNUM <= 10 ORDER BY created_at takes ten arbitrary rows and sorts them. The fixes are to sort in an inline view and apply ROWNUM outside, or, on Oracle 12c and later, to use ORDER BY with FETCH FIRST 10 ROWS ONLY. We also saw why ROWNUM > 10 never returns rows, how to page correctly with a tie breaker, and that Hibernate's Oracle dialect generates the right form for the database version.

What to say in the interviewAbout 90 seconds aloud

Open with

The problem is the order of evaluation. ROWNUM is a pseudocolumn that Oracle assigns as each row is fetched and passes the WHERE clause, and ORDER BY is applied afterwards.

Then, if they want more

So this query reads rows in storage order, stops after ten arbitrary ones, and then sorts those ten. They come back sorted, which is why the bug is easy to miss, but they are not the newest orders. There are two correct versions.

The classic one sorts in an inline view and applies ROWNUM outside: select star from, open bracket, select star from orders order by created_at desc, close bracket, where rownum <= 10. Oracle optimises that into a top-N sort, and with an index on created_at it reads only ten entries.

On 12c and later I would write order by created_at desc fetch first 10 rows only, which is standard SQL and also works on PostgreSQL. For paging I would add id as a tie breaker so pages are deterministic.

I would also point out that where rownum > 10 never returns anything, because the first row fetched is always numbered 1 and is rejected, so ROWNUM paging needs a nested query with an alias. In JPA we normally use setMaxResults and let the Oracle dialect generate fetch first or the ROWNUM wrapper for the database version.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A developer writes SELECT * FROM orders WHERE ROWNUM <= 10 ORDER BY created_at DESC in...": https://scrivio-interview-library.netlify.app/databases/oracle-and-sql-server/a669dcca25/