Home » Mysql » How to add AUTO_INCREMENT to an existing column?

How to add AUTO_INCREMENT to an existing column?

Posted by: admin November 1, 2017 Leave a comment

Questions:

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

Answers:

I think you want to MODIFY the column as described for the ALTER TABLE command. It might be something like this:

ALTER TABLE t1 MODIFY b INTEGER NOT NULL AUTO_INCREMENT;

Questions:
Answers:

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

Questions:
Answers:
Alter table table_name modify column_name datatype(length) AUTO_INCREMENT PRIMARY KEY

You should add primary key to auto increment, otherwise you got error in mysql.

Questions:
Answers:

This worked for me in case you want to change the AUTO_INCREMENT-attribute for a not-empty-table:

1.)Exported the whole table as .sql file
2.)Deleted the table after export
2.)Did needed change in CREATE_TABLE command
3.)Executed the CREATE_TABLE and INSERT_INTO commands from the .sql-file
…et viola

Questions:
Answers:

Simply just add auto_increment Constraint In column or MODIFY COLUMN :-

 ALTER TABLE `emp` MODIFY COLUMN `id` INT NOT NULL UNIQUE AUTO_INCREMENT FIRST;

Or add a column first then change column as –

1. Alter TABLE `emp` ADD COLUMN `id`;

2. ALTER TABLE `emp` CHANGE COLUMN `id` `Emp_id` INT NOT NULL UNIQUE AUTO_INCREMENT FIRST;