Auto-increment is not resetting in MySQL

From what I can see about the alter table statement.

You can reset auto increment value by using the ALTER TABLE statement. The syntax of the ALTER TABLE statement to reset auto increment value is as follows:

ALTER TABLE table_name AUTO_INCREMENT = value;

You specify the table name after the ALTER TABLE clause and the value which we want to reset to in the expression AUTO_INCREMENT = value.

Notice that the value must be greater than or equal to the current maximum value of the auto-increment column.

Which is where your problem lies I suspect. So basically you are left with a couple of options as follows:

  1. TRUNCATE TABLE: which according to our discussion is not a option
  2. DROP and RECREATE the table: A long and painful experience
  3. ALTER auto number column: I have not tried this but you could theoretically alter the primary key column from auto number to a int and then make it a auto number again. Something like:

    ALTER TABLE tblName MODIFY COLUMN pkKeyColumn  BIGINT NOT NULL;
    ALTER TABLE tblName MODIFY COLUMN pkKeyColumn  BIGINT AUTONUMBER NOT NULL;
    

Hope these help a little.


MySQL does not permit you to decrease the AUTO_INCREMENT value, as specified here: http://dev.mysql.com/doc/refman/5.6/en/alter-table.html

You cannot reset the counter to a value less than or equal to the value that is currently in use. For both InnoDB and MyISAM, if the value is less than or equal to the maximum value currently in the AUTO_INCREMENT column, the value is reset to the current maximum AUTO_INCREMENT column value plus one.

Even with your constraints, I would try one of the following:

  1. Explicitly insert your identities for your test data. MySQL doesn't have problems with this, unlike some other database engines
  2. Delete and recreate your identity column (or just change it from being an identity), if the constraints aren't on it itself.
  3. Not use an Identity column and use another method (such as a procedure or outside code) to control your Identity. This is really a last resort and I wouldn't generally recommend it...

Note from OP: It was (1) that was what I needed.

Tags:

Mysql