Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Troubles of adding a new ID (auto increment) after table exist

I have a table with 38.000 records, but without any auto increment column like ID.
Now I have to add an ID column, and I'm wondering could there be troubles?

like image 872
Bobo Avatar asked Jan 28 '11 14:01

Bobo


4 Answers

You can add do that without problem only if your table doesn't have relationship with others.

You must remove the old primary key and upload the table accordingly (perhaps add an unique index on the old primary key).

Proceed like that :

  • Make a dump of your database

  • Remove the primary key like that

ALTER TABLE XXX DROP PRIMARY KEY
  • Add the new column like that
ALTER TABLE XXX add column Id INT NOT NULL AUTO_INCREMENT FIRST, ADD primary KEY Id(Id)

The table will be looked and the AutoInc updated.

like image 131
A.Baudouin Avatar answered Oct 10 '22 20:10

A.Baudouin


This will add an auto increment ID to your MySQL table:

ALTER TABLE  `your_table_name` ADD  `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST;

Depending on the amount of data on your table it could take a few minutes to complete.

like image 24
GoingDrupal Avatar answered Oct 10 '22 20:10

GoingDrupal


This is the solution that i tried with MySQL Workbench:

ALTER TABLE `tableName` CHANGE COLUMN `id` `id` INT(11) NOT NULL AUTO_INCREMENT  ;

I don't know if this is correct way, but I didn't notice any problem in my Java EE Application yet.

like image 21
yurislav Avatar answered Oct 10 '22 19:10

yurislav


I work with very large data and had an id column filled with NULLS. I chose to run the following SQL to fill with numbers... then I set the id column to be my primary key.

set @row = 0;
UPDATE philadelphia.msg_geo_sal SET id = @row := @row + 1;
like image 1
Selah Avatar answered Oct 10 '22 18:10

Selah