How to use Oracle ORDER BY and ROWNUM correctly?
Employ the subquery method in Oracle to efficiently couple ORDER BY
and ROWNUM
. First, sort your data within the subquery, after which you can apply the ROWNUM
filter:
In this manner, your top 10 entries are neatly arranged within the subquery before the application of the row number limit.
Navigating the quirks: ORDER BY, ROWNUM, and WHERE clause
Order matters in Oracle's SQL - a crucial point when combining ORDER BY
and ROWNUM
. The WHERE
clause is executed before ORDER BY
, so if you're using ROWNUM
without a subquery, your results may give you a surprise!
The order of operations
The key to understanding the correct use of ROWNUM
in conjunction with ORDER BY
lies in knowing that ROWNUM
is allocated prior to ordering the rows. Therefore, encapsulating your query in a subquery is not just a good idea, it's a necessity. Without the subquery, you'll get unexpected results, much like ordering a salad and getting a "surprise" dessert instead (and we don't mean this in a good way)!
In this query, ROWNUM
is assigned first, and the ORDER BY
clause has no effect on it, leading to unforeseen and unsorted results.
Look beyond ROWNUM
If you are using Oracle 12c or later, consider the FETCH FIRST
or OFFSET
row limiting clauses. They give your code a tidy, contemporary finish:
The timestamp tango
To retrieve the most recent record, skip the sorting exercise altogether. You can simply use an aggregate function like MAX()
inside a subquery. It's kind of like time travel, but just for your data:
Mind your resources
Just like a buffet, where taking too much food is wasteful, querying unnecessary columns in Oracle can lead to wasted resources. Conveniently select individual columns instead of SELECT *
when you can:
Reducing Time Travel: Embracing TO_DATE and Manual Limitations
Mastering TO_DATE
Oracle's TO_DATE
function can act as your time machine, enabling efficient limitation of results by timestamp:
Working with manual result limitations
When you need to retrieve data between specific times, a custom WHERE
clause within an inner query offers increased performance:
Always keep an eye on design efficiency; consider if inner query-based limitations suit your context.
Was this article helpful?