Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to renumber primary index

Tags:

sql

mysql

I have got a simple MySQL table and primary index (id) is not numbered one by one (1, 31, 35, 100 etc.). I want them to be numbered like (1, 2, 3, 4). Please tell me how to do it. I would also like to point that I am aware of possible consequences of the operation, but I just want to tidy up the table.

like image 622
Kamil Mroczek Avatar asked Apr 15 '10 07:04

Kamil Mroczek


People also ask

Is a primary key automatically an index?

A primary index is automatically created for the primary key and ensures that the primary key is unique. You can use the primary index to retrieve and access objects from the database. The unique index is a column, or an ordered collection of columns, for which each value identifies a unique row.

What is the indexed value of a primary key?

A primary key is unique, whereas an index does not have to be unique. Therefore, the value of the primary key identifies a record in a table, the value of the index not necessarily. Primary keys usually are automatically indexed - if you create a primary key, no need to create an index on the same column(s).

How to ADD id in mysql table?

To add a new AUTO_INCREMENT integer column named c : ALTER TABLE t2 ADD c INT UNSIGNED NOT NULL AUTO_INCREMENT, ADD PRIMARY KEY (c); We indexed c (as a PRIMARY KEY ) because AUTO_INCREMENT columns must be indexed, and we declare c as NOT NULL because primary key columns cannot be NULL .


2 Answers

I agree other methods will work but I'm just giving a different idea. This will do without any temp table creation requirements::

SET @i=0;
UPDATE table_name SET column_name=(@i:=@i+1);
like image 87
kv. Avatar answered Oct 17 '22 12:10

kv.


give a try to renumber method of dalmp (DALMP Database Abstraction Layer for MySQL using PHP.)

$db->renumber('table','uid');

basically it does this:

SET @var_name = 0;
UPDATE Tablename SET ID = (@var_name := @var_name +1);
ALTER TABLE tablename AUTO_INCREMENT = 1
like image 20
tareco Avatar answered Oct 17 '22 13:10

tareco