MySQL AUTO_INCREMENT does not ROLLBACK

codegy picture codegy · Jan 16, 2009 · Viewed 35.8k times · Source

I'm using MySQL's AUTO_INCREMENT field and InnoDB to support transactions. I noticed when I rollback the transaction, the AUTO_INCREMENT field is not rollbacked? I found out that it was designed this way but are there any workarounds to this?

Answer

jmucchiello picture jmucchiello · Jan 16, 2009

It can't work that way. Consider:

  • program one, you open a transaction and insert into a table FOO which has an autoinc primary key (arbitrarily, we say it gets 557 for its key value).
  • Program two starts, it opens a transaction and inserts into table FOO getting 558.
  • Program two inserts into table BAR which has a column which is a foreign key to FOO. So now the 558 is located in both FOO and BAR.
  • Program two now commits.
  • Program three starts and generates a report from table FOO. The 558 record is printed.
  • After that, program one rolls back.

How does the database reclaim the 557 value? Does it go into FOO and decrement all the other primary keys greater than 557? How does it fix BAR? How does it erase the 558 printed on the report program three output?

Oracle's sequence numbers are also independent of transactions for the same reason.

If you can solve this problem in constant time, I'm sure you can make a lot of money in the database field.

Now, if you have a requirement that your auto increment field never have gaps (for auditing purposes, say). Then you cannot rollback your transactions. Instead you need to have a status flag on your records. On first insert, the record's status is "Incomplete" then you start the transaction, do your work and update the status to "compete" (or whatever you need). Then when you commit, the record is live. If the transaction rollsback, the incomplete record is still there for auditing. This will cause you many other headaches but is one way to deal with audit trails.