What is the default order of records for a SELECT statement in MySQL?
Reposting my answer to a similar question regarding SQL Server:
In the SQL world, order is not an inherent property of a set of data. Thus, you get no guarantees from your RDBMS that your data will come back in a certain order -- or even in a consistent order -- unless you query your data with an ORDER BY clause.
So, to answer your question:
- MySQL sorts the records however it wants without any guarantee of consistency.
- If you intend to rely on this order for anything, you must specify your desired order using
ORDER BY
. To do anything else is to set yourself up for unwelcome surprises.
This is a property of all SQL, not just MySQL. The relevant text in the SQL-92 spec is:
If an <order by clause> is not specified, then the ordering of the rows of Q is implementation-dependent.
There are similar bits of text in the spec for cursors.
The order of the rows in the absence of ORDER BY
clause may be:
- different between any two storage engines;
- if you use the same storage engine, it might be different between any two versions of the same storage engine; Example here, scroll down to "Ordering of Rows".
- if the storage engine version is the same, but MySQL version is different, it might be different because of the query optimizer changes between those versions;
- if everything is the same, it could be different due to the moon phase and that is OK.
Insertion is unordered, chaotic, on arrival. The index which is created does have order where elements are inserted in proper location in the linked list which is the index. Think of a triply linked list for an index, where you have a forward moving link from one index element to the next, a backward looking link for the traversal and integrity purposes, and then a set of pointers to the actual records in the table which match the indexed element in question.
Actual data, chaotic in storage. Index associated with the data, ordered in storage and construction. Actual pull of data, ordered or unordered, depends upon the query involved.