Hello friends, As a WAT preparation. Write a sentence on word FRIEND
Home / Groups
Hello friends, As a WAT preparation. Write a sentence on word FRIEND
These groups are good for study purpose.
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:
✅ 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:
? 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!
You need an account to perform this action. If you have account click Login or Create an Account.