Search code examples
mysqlincrementauto-increment

Increment all values in mysql table


Lets say I have

+-------------+--------------+------+-----+---------+-------+
| Field       | Type         | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+-------+
| id          | int(11)      | YES  | UNI | NULL    |       |
| isbn        | varchar(20)  | NO   |     | NULL    |       |
| title       | varchar(200) | YES  |     | NULL    |       |
| author      | varchar(200) | YES  |     | NULL    |       |
+-------------+--------------+------+-----+---------+-------+

The primary key was isbn (which I have now removed and I have added id (i will make primary soon) before I can do this i need to make sure that all id's are unique (so I want to update all values to increment starting at 1;

I have tried the following but it isn't working any suggestions?

SET @bookid = 1; UPDATE books SET `id` = @bookid + 1;

Solution

  • Use this:

    ALTER TABLE books AUTO_INCREMENT=1;
    

    or if you haven't already id column, also add it

    ALTER TABLE books ADD id INT UNSIGNED NOT NULL AUTO_INCREMENT,
        ADD INDEX (id);