Skip to main content
1 of 3
J.D.
  • 39.5k
  • 12
  • 60
  • 134

The order of the results of a SELECT query are never guaranteed when there's no ORDER BY clause specified. This is true in pretty much all modern relational database systems (as per the SQL standard).

You can find more information specific to MySQL in this DBA.StackExchange.com answer:

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.

  • 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.

To your question "«Then why is it always the last one?»":

You can almost attribute this to luck, on repeated runs. As mentioned above "MySQL sorts the records however it wants". What this really means is that the algorithm of the database engine returns the rows based on the results of a multitude of operations that it goes through under the hood. For now, it appears to be in a repeatable order, but because of the complexity of the database engine and that promised lack of guarantee without an ORDER BY clause, it will not always be repeatable and can change for a multitude of reasons, unexpectedly. So you should not rely on the ordering you see today to be the same one you'll see in the future.

J.D.
  • 39.5k
  • 12
  • 60
  • 134