26
votes

I've got a table in MySQL that has a Primary Key Column.

Lets say:

ID | Value
1  | One
2  | Two
6  | Three
8  | Four
9  | Five

How do I get it to be:

ID | Value
1  | One
2  | Two
3  | Three
4  | Four
5  | Five

There are no other tables. Just the one. I just want the ID to be in a proper series.

Any suggestion?? A Query perhaps.. :)

3
I know about Ordering. That's not what I want.. I want the ID to be in a Perfect Sequence...LearningDeveloper

3 Answers

58
votes

There is even a simple way to accomplish the result by writing this query

SET @newid=0;
UPDATE tablename SET primary_key_id=(@newid:=@newid+1) ORDER BY primary_key_id;

This query will reindex the primary key starts from 1

11
votes

Seems to me you have two options.

1) create a new table and copy the existing data over.

2) add another autoincrement field to the existing table, then delete the original column.

ALTER TABLE tableName ADD NewIdn INT NOT NULL AUTO_INCREMENT KEY
0
votes

I did this in phpmyadmin by unchecking the A_I box (Auto Increment setting), clicking save, and then checking it again, and clicking save again.