Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a Primary key to a MySQL table, and auto-populating it

I have a bunch of huge tables that don't have primary keys. (Don't ask me why) I will append an 'id' field to each table. It will be an integer type. Later, I will promote it to a non-null, unique-value index, and a primary key.

My question: Is there a way in MySQL (5 ish) We have about a hundred tables, and the largest among them have over 1 million records. After creating the new 'id' column, is there a way to have MySQL backfill (ie, add a value to the existing records) the 'id' field? I would rather be able to do this all in MySQL. Otherwise I will have to write a PHP script to populate the existing records.

Thanx, Don!

like image 316
Don Briggs Avatar asked Sep 20 '11 20:09

Don Briggs


People also ask

Does MySQL auto increment primary key?

One of the important tasks while creating a table is setting the Primary Key. The Auto Increment feature allows you to set the MySQL Auto Increment Primary Key field. This automatically generates a sequence of unique numbers whenever a new row of data is inserted into the table.

Can a primary key be auto increment?

Auto-increment allows a unique number to be generated automatically when a new record is inserted into a table. Often this is the primary key field that we would like to be created automatically every time a new record is inserted.

How do I change my primary key to auto increment?

To change a primary key to auto_increment, you can use MODIFY command. Let us first create a table. Look at the above sample output, StudentId column has been changed to auto_increment.


1 Answers

If you do a

ALTER TABLE table1 ADD COLUMN id INTEGER NOT NULL auto_increment PRIMARY KEY

It will auto populate your table with a auto_incrementing primary key.

Might take a while on a large table.

like image 75
Johan Avatar answered Oct 20 '22 15:10

Johan