Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reuse identity value after deleting rows

Is it possible to reuse an identity field value after deleting rows in SQL Server 2008 Express? Here is an example. Suppose I have a table with an Id field as a primary key (identity). If I add five rows, I will have these 5 Ids: 1, 2, 3, 4, 5. If I were to delete these rows, and then add five more, the new rows would have Ids: 6, 7, 8, 9, 10. Is it possible to let it start over at 1 again?

Do I have to delete data from another table in order to accomplish this? Thanks for your help.

like image 610
Jeremy Avatar asked Nov 26 '10 19:11

Jeremy


People also ask

Does SQL Server reuse IDs?

No, SQL Server won't reuse IDs.

How do you change the seed value of an identity column?

To change the original seed value and reseed any existing rows, drop the identity column and recreate it specifying the new seed value. When the table contains data, the identity numbers are added to the existing rows with the specified seed and increment values.

Can we delete row with primary key?

If you know the value of the primary key for the row that you want to delete, you can specify the value using the VIA clause. If there is more than one primary key column, the values must be specified in order and separated by commas (,). String values must be enclosed in single quotes (').


2 Answers

You can use the following to set the IDENTITY value:

DBCC CHECKIDENT (orders, RESEED, 999)

That means you'll have to run the statement based on every DELETE. That should start to highlight why this is a bad idea...

The database doesn't care about sequential values - that's for presentation only.

like image 79
OMG Ponies Avatar answered Nov 02 '22 08:11

OMG Ponies


If you want to reset the identity after deleting all rows then do one of these

--instead of delete, resets identity value
TRUNCATE TABLE orders

--or if TRUNCATE fails because of FKs, use this after DELETE
DBCC CHECKIDENT (orders, RESEED, 1)

Otherwise, the internal value should not matter whether gaps or not.

like image 45
gbn Avatar answered Nov 02 '22 10:11

gbn