Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reset autoincrement in Microsoft SQL Server 2008 R2

I created a primary key to be autoincrement.

  • I added two rows: ID=1, ID=2
  • I deleted these two rows.
  • I added a new row, but the new row's ID was: ID=3

How can I reset or restart the autoincrement to 1?

like image 633
victorio Avatar asked Dec 13 '12 10:12

victorio


People also ask

How do I reset Autoincrement?

In MySQL, the syntax to reset the AUTO_INCREMENT column using the ALTER TABLE statement is: ALTER TABLE table_name AUTO_INCREMENT = value; table_name. The name of the table whose AUTO_INCREMENT column you wish to reset.

How do I set Autoincrement value?

In MySQL, the syntax to change the starting value for an AUTO_INCREMENT column using the ALTER TABLE statement is: ALTER TABLE table_name AUTO_INCREMENT = start_value; table_name. The name of the table whose AUTO_INCREMENT value you wish to change.

Is Autoincrement primary key?

Auto-increment allows a unique number to be generated automatically when a new record is inserted into a table. Often this is the primary key field that we would like to be created automatically every time a new record is inserted.

How do I find my Autoincrement ID?

The starting value for AUTO_INCREMENT is 1, which is the default. It will get increment by 1 for each new record. To get the next auto increment id in MySQL, we can use the function last_insert_id() from MySQL or auto_increment with SELECT. Creating a table, with “id” as auto-increment.


2 Answers

If you use the DBCC CHECKIDENT command:

 DBCC CHECKIDENT ("YourTableNameHere", RESEED, 1); 

But use with CAUTION! - this will just reset the IDENTITY to 1 - so your next inserts will get values 1, then 2, and then 3 --> and you'll have a clash with your pre-existing value of 3 here!

IDENTITY just dishes out numbers in consecutive order - it does NOT in any way make sure there are no conflicts! If you already have values - do not reseed back to a lower value!

like image 152
marc_s Avatar answered Sep 28 '22 12:09

marc_s


I'm using SQL Server 2012 and the DBCC CHECKIDENT ("YourTableNameHere", RESEED, 1) causes a value of 2 on the very next insert.

So for SQL Server 2012, change the 1 to 0 to get a value of 1 for your next record insert:

DBCC CHECKIDENT ("YourTableNameHere", RESEED, 0);  -- value will be 1 for the next record insert 
like image 26
user2309101 Avatar answered Sep 28 '22 10:09

user2309101