Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reset the primary key of a table?

In my table tbphotos I had a 100 records. I then deleted all the records and now that I want to restart data entry I see that my primary key doesn't start from 1, but it starts from 101,

Is there any way to reset the primary key?

I am using MySQL administrator account.

like image 728
Kaveh Avatar asked Nov 27 '09 17:11

Kaveh


People also ask

How do I reset my primary key ID?

alter table yourTableName AUTO_INCREMENT=1; truncate table yourTableName; After doing the above two steps, you will get the primary key beginning from 1.

How do I change the primary key in a table?

To change the primary key of a table, delete the existing key using a DROP clause in an ALTER TABLE statement and add the new primary key.

Can we reset the primary key column value?

The reset the primary key of a table means to reset the auto_increment property to 1. The syntax is as follows to reset the primary key of a table.

How can reset primary key ID after delete the row?

So add one to that number and run the following command: ALTER TABLE `table` AUTO_INCREMENT = number; Replacing 'number' with the result of the previous command plus one and replacing table with the table name. If you deleted all the rows in the table, then you could run the alter table command and reset it to 0.


2 Answers

alter table foo AUTO_INCREMENT = 1

like image 51
Donnie Avatar answered Oct 16 '22 10:10

Donnie


You can reset the auto-increment like this:

ALTER TABLE tablename AUTO_INCREMENT = 1 

But if you are relying on the autoincrement values, your program is very fragile. If you need to assign consecutive numbers to your records for your program to work you should create a separate column for that, and not use a database auto-increment ID for this purpose.

like image 20
Mark Byers Avatar answered Oct 16 '22 11:10

Mark Byers