Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update id set from 1?

I have an id i.e primary key and auto increment. Is there any query to update my existing id and make my id start from 1 and next id 2 and so on..

For example

id  name
3   ABC
5   XYZ
9   PQR

NOTE: id is already primary and auto increment and I don't want truncate my id.

if possible i want to get

id  name
1   ABC
2   XYZ
3   PQR

ALTER TABLE table AUTO_INCREMENT = 1; is not my solution.

Thanks

like image 434
Krity Shrestha Avatar asked Mar 31 '17 09:03

Krity Shrestha


People also ask

How to auto increment?

The MS SQL Server uses the IDENTITY keyword to perform an auto-increment feature. In the example above, the starting value for IDENTITY is 1, and it will increment by 1 for each new record. Tip: To specify that the "Personid" column should start at value 10 and increment by 5, change it to IDENTITY(10,5) .

How to auto increment id in MySQL?

MySQL uses the AUTO_INCREMENT keyword to perform an auto-increment feature. By default, the starting value for AUTO_INCREMENT is 1, and it will increment by 1 for each new record. VALUES ('Lars','Monsen'); The SQL statement above would insert a new record into the "Persons" table.

How do I change identifier in MySQL?

Enter the following command in your MySQL client shell to change the name of the column and its definition: ALTER TABLE table_name CHANGE old_column_name new_col_name Data Type; You can change the data type of the column or keep the existing one.


1 Answers

Of course there is a way:

set @counter = 0;
update table_name
set id  = (@counter := @counter + 1);

EDIT

To avoid problem with duplicate keys you can run something like this before to temporary change current ids to negative equivalents:

update table_name
set id  = 0 - id;
like image 59
luk4ward Avatar answered Oct 05 '22 11:10

luk4ward