Frage

Is it safe to assume when reading a MySQL table line by line from an application that the table will always read from top to bottom, one after the other in perfect sequential order.

E.G. If a table is ordered by a unique ID and I read it in via C++ one line at a time. Is it safe to assume I will get each line in exact unique ID order every time.

My gut feeling is that it is not a safe assumption but I have no technical reasoning for that.

My testing has always shown that it does provide table rows in order but it makes me nervous relying on it. As a result I write programs such that they do not depend on this assumption which makes them a little more complicated and a little less efficient.

Thanks C

War es hilfreich?

Lösung

If you are using the standard C++ MySQL connector, then according to the reference manual, "The preview version does buffer all result sets on the client to support cursors".

It has also generally been my experience that your result sets are buffered, and therefore do not change when the underlying table changes.

Andere Tipps

If you use the following query you should have no issues,

SELECT columns
FROM tables
WHERE predicates
ORDER BY column ASC/DESC;

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top