Oracle SQL returns rows in arbitrary fashion when no "order by" clause is used

jgunnink picture jgunnink · Sep 21, 2010 · Viewed 9.4k times · Source

Maybe someone can explain this to me, but when querying a data table from Oracle, where multiple records exist for a key (say a customer ID), the record that appears first for that customer can vary if there is no implicit "order by" statement enforcing the order by say an alternate field such as a transaction type. So running the same query on the same table could yield a different record ordering than from 10 minutes ago.

E.g., one run could yield:

Cust_ID, Transaction_Type
123 A
123 B

Unless an "order by Transaction_Type" clause is used, Oracle could arbitrarily return the following result the next time the query is run:

Cust_ID, Transaction_Type
123 B
123 A

I guess I was under the impression that there was a database default ordering of rows in Oracle which (perhaps) reflected the physical ordering on the disk medium. In other words, an arbitrary order that is immutable and would guarantee the same result when a query is rerun.

Does this have to do with the optimizer and how it decides where to most efficiently retrieve the data?

Of course the best practice from a programming perspective is to force whatever ordering is required, I was just a little unsettled by this behavior.

Answer

Adam Musch picture Adam Musch · Sep 21, 2010

The order of rows returned to the application from a SELECT statement is COMPLETELY ARBITRARY unless otherwise specified. If you want, need, or expect rows to return in a certain order, it is the user's responsibility to specify such an order.

(Caveat: Some versions of Oracle would implicitly sort data in ascending order if certain operations were used, such as DISTINCT, UNION, MINUS, INTERSECT, or GROUP BY. However, as Oracle has implemented hash sorting, the nature of the sort of the data can vary, and lots of SQL relying on that feature broke.)