I have a MySQL table with a primary key field that has AUTO_INCREMENT on. After reading other posts on here I\'ve noticed people with the same problem and with varied answer
You may think about making a trigger after delete so you can update the value of autoincrement and the ID value of all rows that does not look like what you wanted to see.
So you can work with the same table and the auto increment will be fixed automaticaly whenever you delete a row the trigger will fix it.
Try :
SET @num := 0;
UPDATE your_table SET id = @num := (@num+1);
ALTER TABLE
tableName
AUTO_INCREMENT = 1;
That'll reset the autoincremented value, and then count every row while a new value is created for it.
example : before
so the table will display the array : 1,2,4,5
Example : AFTER (if you use this command you will obtain)
No trace of the deleted value, and the rest of the incremented continues with this new count.
BUT
Primary autoincrement keys in database are used to uniquely identify a given row and shouldn't be given any business meaning. So leave the primary key as is and add another column called for example courseOrder
. Then when you delete a record from the database you may want to send an additional UPDATE statement in order to decrement the courseOrder
column of all rows that have courseOrder
greater than the one you are currently deleting.
As a side note you should never modify the value of a primary key in a relational database because there could be other tables that reference it as a foreign key and modifying it might violate referential constraints.
I came here looking for an answer to the Title question "MySQL - Auto Increment after delete"
but I could only find an answer for that in the questions
By using something like:
DELETE FROM table;
ALTER TABLE table AUTO_INCREMENT = 1;
Note that Darin Dimitrov's answer explain really well AUTO_INCREMENT
and it's usage. Take a look there before doing something you might regret.
PS: The question itself is more "Why you need to recycle key values?"
and Dolph's answer cover that.
There is actually a way to fix that. First you delete the auto_incremented primary key column, and then you add it again, like this:
ALTER TABLE table_name DROP column_name;
ALTER TABLE table_name ADD column_name int not null auto_increment primary key first;