Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resetting the primary key to 1 after deleting all the data

So i have MySql and i have a table user with a user_id column and it is the primary key and auto incremented. Now when i delete all my data from the table and add the new one, the user_id does not start from 1 but from the number it had before deletion. What if i want to reset it without dropping the whole table and creating it again.

like image 598
Kraken Avatar asked Aug 07 '11 10:08

Kraken


People also ask

How do I change my primary key back to 1?

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

What happens when you delete primary key?

You can delete (drop) a primary key in SQL Server by using SQL Server Management Studio or Transact-SQL. When the primary key is deleted, the corresponding index is deleted. This may be the clustered index of the table, causing the table to become a heap.

Can we reset the primary key column value?

If you use TRUNC instead of manually deleting records, your primary key will be reset.


2 Answers

ALTER TABLE some_table AUTO_INCREMENT=1

So some_table would be the table you want to alter.

You could also use:

TRUNCATE TABLE some_table

This will reset the Auto Increment on the table as well as deleting all records from that table.

like image 144
Elgoog Avatar answered Oct 18 '22 22:10

Elgoog


The code below is best if you have some data in the database already but want to reset the user_id to 1 without deleting the data. Copy and run in SQL command

ALTER TABLE members DROP user_id;
ALTER TABLE members AUTO_INCREMENT = 1;
ALTER TABLE members ADD user_id int UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST;
like image 37
icynets Avatar answered Oct 18 '22 22:10

icynets