Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query to Re-index Primary Key of MySQL Database

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

like image 241
LearningDeveloper Avatar asked Apr 20 '12 07:04

LearningDeveloper


People also ask

How do I re index in MySQL?

Luckily, it's easy for MySQL to optimize index data for MyISAM tables. You can use the OPTIMIZE TABLE command to reindex a table. In doing so, MySQL will reread all the records in the table and reconstruct all of its indexes. The result will be tightly packed indexes with good statistics available.

Can you index a primary key?

Yes, primary key is automatically indexed in MySQL because primary key, index, etc gets stored into B-trees. All engines including InnoDB as well as MyISAM automatically supports the primary key to be indexed. The primary key is implicitly indexed in InnoDB, MyISAM, and other engines.

Can we change the index of primary key on table?

Short answer: yes you can.

Can we apply index on primary key in SQL?

You can define a primary key in SQL Server by using SQL Server Management Studio or Transact-SQL. Creating a primary key automatically creates a corresponding unique clustered index, or a nonclustered index if specified as such.


1 Answers

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

like image 165
Yogesh Suthar Avatar answered Sep 29 '22 10:09

Yogesh Suthar