Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

Behavior of IDENTITY columns

Have you ever noticed unexpected gaps in sequences in IDENTITY columns? You find that there are missing values in what should be an unbroken sequence of numbers. The problem could be partially related to transaction rollbacks. Conventional thinking/approach would lead one to believe that a rolled back transaction would undo the logged data changes to a table. While a rollback will remove the data rows included in a transaction, it does not reset the identity value to its previous setting. We can see this demonstrated in a brief example. First, lets create a table with an identity column and insert some data: CREATE TABLE #TestTable ( ID INT IDENTITY(1,1) , Value VARCHAR(20) NULL ) INSERT #TestTable VALUES ('Red') , ('Green') , ('Blue') Now well check the identity value by running: DBCC CHECKIDENT(#TestTable) Which should return 3, the current identity value of the table. Next, well start a transaction, insert a few rows, and the roll back our changes. BEGIN TRAN INSERT #TestTable VALUES ('White') , ('Orange') , ('Black') ROLLBACK TRAN We just inserted three rows but rolled back the transaction, so the new rows were never committed. However, if you check the identity value again, youll see its been incremented to 6 even though no new rows have been committed to the table.

This is actually intended behavior and not a bug in the product. If you think through some concurrency scenarios, you can understand why identity columns would be handled in this manner. However, you can reset the identity value using the same DBCC command listed below.

DBCC CHECKIDENT (#TestTable, RESEED, @oldID) WITH NO_INFOMSGS;

Here @oldID is where to which you want to reset the Identity coloumn. For example: DBCC CHECKIDENT (#TestTable, RESEED, 3) WITH NO_INFOMSGS;

Now if you check, it would again return 3. DBCC CHECKIDENT(#TestTable)

But you should make sure you understand the potential effects of doing so before you roll it out to your production systems.

You might also like