Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add AUTO_INCREMENT to an existing column?

How do I add auto_increment to an existing column of a MySQL table?

like image 881
mpen Avatar asked Feb 17 '11 23:02

mpen


People also ask

How do I add an auto increment to an existing column?

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.

How can add auto increment to column in SQL Server?

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) .

How do I create an existing column auto increment in Oracle?

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.


2 Answers

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.

like image 179
Don Kirkby Avatar answered Oct 07 '22 01:10

Don Kirkby


Method to add AUTO_INCREMENT to a table with data while avoiding “Duplicate entry” error:

  1. Make a copy of the table with the data using INSERT SELECT:

    CREATE TABLE backupTable LIKE originalTable;  INSERT backupTable SELECT * FROM originalTable; 
  2. Delete data from originalTable (to remove duplicate entries):

    TRUNCATE TABLE originalTable; 
  3. To add AUTO_INCREMENT and PRIMARY KEY

    ALTER TABLE originalTable ADD id INT PRIMARY KEY AUTO_INCREMENT; 
  4. 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; 
  5. 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

like image 44
Arian Acosta Avatar answered Oct 07 '22 02:10

Arian Acosta