As I know, from the relational database theory, a select
statement without an order by
clause should be considered to have no particular order. But actually in SQL Server and Oracle (I've tested on those 2 platforms), if I query from a table without an order by
clause multiple times, I always get the results in the same order. Does this behavior can be relied on? Anyone can help to explain a little?
Sql-server – The order of a SQL Select statement without Order By clause
oracleselectsql serversql-order-by
Related Topic
- Sql – Parameterize an SQL IN clause
- Sql – Exclude a column using SELECT * [except columnA] FROM tableA
- Sql – How to do an UPDATE statement with JOIN in SQL Server
- Sql – How to UPDATE from a SELECT in SQL Server
- SQL SELECT WHERE field contains words
- Sql – Can we have multiple “WITH AS” in single sql – Oracle SQL
Best Answer
No, that behavior cannot be relied on. The order is determined by the way the query planner has decided to build up the result set. simple queries like
select * from foo_table
are likely to be returned in the order they are stored on disk, which may be in primary key order or the order they were created, or some other random order. more complex queries, such asselect * from foo where bar < 10
may instead be returned in order of a different column, based on an index read, or by the table order, for a table scan. even more elaborate queries, with multipewhere
conditions,group by
clauses,union
s, will be in whatever order the planner decides is most efficient to generate.The order could even change between two identical queries just because of data that has changed between those queries. a "where" clause may be satisfied with an index scan in one query, but later inserts could make that condition less selective, and the planner could decide to perform a subsequent query using a table scan.
To put a finer point on it. RDBMS systems have the mandate to give you exactly what you asked for, as efficiently as possible. That efficiency can take many forms, including minimizing IO (both to disk as well as over the network to send data to you), minimizing CPU and keeping the size of its working set small (using methods that require minimal temporary storage).
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.If you care about efficiency, but not order, skip the
ORDER BY
clause. If you care about the order but not efficiency, use theORDER BY
clause.Since you actually care about BOTH use
ORDER BY
and then carefully tune your query and database so that it is efficient.