How do I add auto_increment
to an existing column of a MySQL table?
If you're looking to add auto increment to an existing table by changing an existing int column to IDENTITY , SQL Server will fight you. You'll have to either: Add a new column all together with new your auto-incremented primary key, or. Drop your old int column and then add a new IDENTITY right after.
The MS SQL Server uses the IDENTITY keyword to perform an auto-increment feature. In the example above, the starting value for IDENTITY is 1, and it will increment by 1 for each new record. Tip: To specify that the "Personid" column should start at value 10 and increment by 5, change it to IDENTITY(10,5) .
You can double click the name of the column or click on the 'Properties' button. Column Properties dialog box appears. Select the General Tab (Default Selection for the first time). Then select both the 'Auto Increment' and 'Identity Column' check boxes.
I think you want to MODIFY
the column as described for the ALTER TABLE
command. It might be something like this:
ALTER TABLE users MODIFY id INTEGER NOT NULL AUTO_INCREMENT;
Before running above ensure that id
column has a Primary index.
Method to add AUTO_INCREMENT to a table with data while avoiding “Duplicate entry” error:
Make a copy of the table with the data using INSERT SELECT:
CREATE TABLE backupTable LIKE originalTable; INSERT backupTable SELECT * FROM originalTable;
Delete data from originalTable (to remove duplicate entries):
TRUNCATE TABLE originalTable;
To add AUTO_INCREMENT and PRIMARY KEY
ALTER TABLE originalTable ADD id INT PRIMARY KEY AUTO_INCREMENT;
Copy data back to originalTable (do not include the newly created column (id), since it will be automatically populated)
INSERT originalTable (col1, col2, col3) SELECT col1, col2,col3 FROM backupTable;
Delete backupTable:
DROP TABLE backupTable;
I hope this is useful!
More on the duplication of tables using CREATE LIKE:
Duplicating a MySQL table, indexes and data
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With