Is there a way? Well, yes there is. It basically involves writing the update as:
- Lock the table so no threads can even attempt an insert or update.
- Find the maximum id in the table and add 1.
- Insert a new row with the new id.
- Unlock the table.
In general, databases don't let you lock the entire table. So, you have implement additional mechanisms to handle this -- basically, user a user-implemented semaphore (you can Wikipedia that).
This results in lots of additional, error-prone code, but it can be done. It causes inserts to be much slower, because you are locking threads out of the table for a long time. There is a really good reason why databases don't do this.
Do the gaps have any affect on the performance of the database? Pretty much no effect at all. I suppose there are potential issues with running out of ids, but that issue is rather remove.
If the only cause of the gaps is invalid data, then you can minimize the occurrence by checking the data using a select
before doing an insert
. This does not "fix" the problem, because two independent threads could still attempt to insert the same data at the same time. In addition, some databases allocate blocks of numbers under some circumstances. I'm not sure if MySQL ever does this.