You are right. It is not safe to assume when reading a MySQL table line by line from an application that the table will always be read from top to bottom, one after the other in perfect sequential order. It is not safe to assume that if a table is ordered by a unique ID and I read it in (via C++ or otherwise) one line at a time, you will get each line in exact unique ID order every time.
There is no guarantee for that, on any RDBMS. No one should rely on that assumption.
Rows have no (Read: should not have) intrinsic or default order in relational tables. Tables (relations) are, by definition, unordered sets or rows.
What gives this impression is that most systems, when asked to return a result for a query like:
SELECT columns
FROM table
they retrieve all the rows from the disk, reading the whole file. So, they return the rows (usually) in the order they were stored in the file or in the order of the clustered key (e.g. in InnoDB tables in MySQL). So, they return the result with the same order every time.
If there are multiple tables in the FROM
clause or if there are WHERE
conditions, it's a whole different situation, as not the whole tables are read, different indexes may be used, so the system may not read the tables files but just the index files. Or read a small part of the tables.
It's also a different story if you have partitioned tables or distributed databases.
Conclusion is that you should have an ORDER BY
part in your queries, if you want to guarantee the same order every time.