patternsqlMajor
Reset IDENTITY value
Viewed 0 times
identityresetvalue
Problem
I have a table with an IDENTITY column. While developing I delete the rows from time to time and add them again. But the IDENTITY values always kept increasing and didn't start from 1 when I added them again. Now my id's go from 68 -> 92 and this crashes my code.
How do I reset the IDENTITY value?
How do I reset the IDENTITY value?
Solution
You can reset the identity value by
So next time you insert into TableName, the identity value inserted will be 1.
When you delete rows from the table, it will not reset the Identity value, but it will keep increasing it. Just like what happened in your case.
Now when you truncate the table, it will reset the Identity value to its original Seed value of the table.
Refer to : SQL SERVER – DELETE, TRUNCATE and RESEED Identity for a detailed example and some good explanation of Difference between Truncate and Delete
DBCC CHECKIDENT('tableName', RESEED, 0)So next time you insert into TableName, the identity value inserted will be 1.
When you delete rows from the table, it will not reset the Identity value, but it will keep increasing it. Just like what happened in your case.
Now when you truncate the table, it will reset the Identity value to its original Seed value of the table.
Refer to : SQL SERVER – DELETE, TRUNCATE and RESEED Identity for a detailed example and some good explanation of Difference between Truncate and Delete
Code Snippets
DBCC CHECKIDENT('tableName', RESEED, 0)Context
StackExchange Database Administrators Q#43910, answer score: 30
Revisions (0)
No revisions yet.