Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When no 'Order by' is specified, what order does a query choose for your record set?

I was always of the impression that a query with no specified 'Order by' rule, would order this by the results by what was specified within your where clause.

For instance, my where clause states:

WHERE RESULTS_I_AM_SEARCHING_FOR IN ITEM 1 ITEM 2 ITEM 3 

I would have imagined that the results returned for items 1, 2 and 3 would be in the order specified in the where, however this is not the case. Does anyone know what order it sorts them in when not specified?

Thanks and sorry for the really basic question!

Damon

like image 584
dmoney Avatar asked Nov 18 '13 14:11

dmoney


People also ask

When a query does not have an ORDER BY clause What is the order in which the rows are returned?

If you don't specify an ORDER BY , then there is NO ORDER defined. The results can be returned in an arbitrary order - and that might change over time, too.

What is the default order when there is no SQL order specified?

By default, SQL Server sorts out results using ORDER BY clause in ascending order. Specifying ASC in order by clause is optional.

What is true about the result of a query without an ORDER BY clause?

without an ORDER BY clause, you will have not asked exactly for a particular order, and so the RDBMS will give you those rows in some order that (maybe) corresponds with some coincidental aspect of the query, based on whichever algorithm the RDBMS expects to produce the data the fastest.


1 Answers

If you don't specify an ORDER BY, then there is NO ORDER defined.

The results can be returned in an arbitrary order - and that might change over time, too.

There is no "natural order" or anything like that in a relational database (at least in all that I know of). The only way to get a reliable ordering is by explicitly specifying an ORDER BY clause.

Update: for those who still don't believe me - here's two excellent blog posts that illustrate this point (with code samples!) :

  • Conor Cunningham (Architect on the Core SQL Server Engine team): No Seatbelt - Expecting Order without ORDER BY
  • Alexander Kuznetsov: Without ORDER BY, there is no default sort order (post in the Web Archive)
like image 146
marc_s Avatar answered Sep 18 '22 20:09

marc_s