I have inserted records into a SQL Server database table. The table had a primary key defined and the auto increment identity seed is set to “Yes”. This is done primarily because in SQL Azure, each table has to have a primary key and identity defined.
But since I have to delete some records from the table, the identity seed for those tables will be disturbed and the index column (which is auto-generated with an increment of 1) will get disturbed.
How can I reset the identity column after I deleted the records so that the column has sequence in ascending numerical order?
The identity column is not used as a foreign key anywhere in database.
The
DBCC CHECKIDENT
management command is used to reset identity counter. The command syntax is:Example:
It was not supported in a previous versions of Azure SQL Database, but is supported now.
Please note that
new_reseed_value
argument is varied across SQL Server versions according to documentation:However, I find this information misleading (just plain wrong actually) because observed behaviour indicates that at least SQL Server 2012 is still uses new_reseed_value + the current increment value logic. Microsoft even contradicts with its own
Example C
found on same page:Still, this all leaves an option for different behaviour on newer SQL Server versions. I guess the only way to be sure, until Microsoft clear up things in its own documentation, is to do actual tests before usage.
Where 0 is
identity
Start valueIt should be noted that IF all of the data is being removed from the table via the
DELETE
(i.e. noWHERE
clause), then as long as a) permissions allow for it, and b) there are no FKs referencing the table (which appears to be the case here), usingTRUNCATE TABLE
would be preferred as it does a more efficientDELETE
and resets theIDENTITY
seed at the same time. The following details are taken from the MSDN page for TRUNCATE TABLE:So the following:
Becomes just:
Please see the
TRUNCATE TABLE
documentation (linked above) for additional information on restrictions, etc.Truncate
table is preferred because it clears the records, resets the counter and reclaims the dis space.Delete
andCheckIdent
should be used only where foreign keys prevent you from truncatingI tried
@anil shahs
answer and it reset the identity. But when a new row was inserted it got theidentity = 2
. So instead I changed the syntax to:Then the first row will get the identity = 1.
Reset identity column with new id...