Post

No, ROWNUM in Oracle does not guarantee that you'll get the top row based on an ORDER BY. This is a common misconception.

❌ Wrong Way (Misleading)

SELECT *
FROM my_table
WHERE ROWNUM = 1
ORDER BY id ASC;

This does not work as expected. Why?

⚠️ Reason:

  • ROWNUM is assigned before the ORDER BY is applied.
  • So Oracle picks any row, labels it ROWNUM = 1, and then sorts afterward — which defeats the purpose.

✅ Correct Way to Get Top Row Ordered by id ASC

You must use a subquery to apply ORDER BY first, then apply ROWNUM.

SELECT *
FROM (
    SELECT *
    FROM my_table
    ORDER BY id ASC
)
WHERE ROWNUM = 1;

✅ Why This Works:

  • The inner query orders the rows by id ASC.
  • The outer query picks the first row (ROWNUM = 1) from the ordered result.

? Bonus: Top N rows

To get the top 10 rows ordered by ID:

SELECT *
FROM (
    SELECT *
    FROM my_table
    ORDER BY id ASC
)
WHERE ROWNUM <= 10;

✅ Oracle 12c+ Way: Use FETCH FIRST

If you're using Oracle 12c or newer, this is cleaner:

SELECT *
FROM my_table
ORDER BY id ASC
FETCH FIRST 1 ROWS ONLY;

This is ANSI SQL style and preferred in modern Oracle versions.

Let me know if you want examples with pagination, filtering, or analytic functions!

Login to discuss.

You need an account to perform this action. If you have account click Login or Create an Account.


Create an account | Already have account? Login