I think this is true, but I haven't found anything on the web to confirm it. I can get the first id generated for the autoincrement field using last_insert_id(), but can I assume that the next records will have sequential IDs? Or could another user grab an id so that the resulting IDs are not sequential?
Example: insert into mytable (asdf, qwer) values (1,2), (3,4), (5,6), ... , (10000,10001);
If mytable has an autoincrement column, and if two users run this statement at the same time, will one user grab 10000 sequential IDs, and the other user the next 10000 sequential IDs? How about for hundreds of users?
Thanks.
It depends on the storage engine used.
innodb_autoinc_lock_mode
is set to interleaved (2), the inserted rows will have sequential ID's. By default InnoDB runs in consecutive
mode since 5.1 and traditional
mode prior.For more on the innodb_autoinc_lock_mode
option, see 13.6.4.3. AUTO_INCREMENT Handling in InnoDB
If you use LOCK TABLES, the batches should grab sequential id's.
Example:
LOCK TABLES users WRITE;
<BULK INSERT HERE>
UNLOCK TABLES;
This will prevent multiple threads from writing to the table at the same time.
A multi-row insert is just a bulk-operation that performs the same operation over and over again. When an insert statement is fired, it fires a trigger that generates the ID.
So if the database engine used, performs all of its work in a sequential way (queue like - first-in first-out) then yes, sequential id's will be one increment higher than the previous id; if the data is inserted in a multi-threaded way where statements are fired in parallel, then no, id's will be given at "random".
I am not aware of any mysql engine that guarantees this, but then again I haven't made much research in this specific subject.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With