Identity values are very useful, but there can be misconceptions about the way in which they work. One of the more interesting things that I see people assuming is that an identity value will ensure you have a continuous range of values for that column. They assume that this code:
CREATE TABLE MyTable
( id INT IDENTITY(1,1)
)
GO
INSERT mytable DEFAULT VALUES
INSERT mytable DEFAULT VALUES
INSERT mytable DEFAULT VALUES
INSERT mytable DEFAULT VALUES
INSERT mytable DEFAULT VALUES
GO
SELECT * FROM mytable
GO
DROP TABLE dbo.MyTable
It will, and it will get give you a list of 5 rows, with continuous values. Assuming that this pattern continues in your application, you will have a continuous list of values. What about this code?
CREATE TABLE MyTable
( id INT IDENTITY(1,1)
)
GO
INSERT mytable DEFAULT VALUES
INSERT mytable DEFAULT VALUES
INSERT mytable DEFAULT VALUES
INSERT mytable DEFAULT VALUES
INSERT mytable DEFAULT VALUES
GO
UPDATE mytable SET id = 12
WHERE id = 3
go
SELECT * FROM mytable
GO
DROP TABLE dbo.MyTable
You’ll actually get an error, since you can’t specify identity values directly, but you can do this:
CREATE TABLE MyTable
( id INT IDENTITY(1,1)
)
GO
INSERT mytable DEFAULT VALUES
INSERT mytable DEFAULT VALUES
INSERT mytable DEFAULT VALUES
INSERT mytable DEFAULT VALUES
INSERT mytable DEFAULT VALUES
GO
DELETE mytable WHERE id = 3
GO
SELECT * FROM mytable
GO
That will give me these results:
If I now do this:
INSERT mytable DEFAULT VALUES
GO
SELECT * FROM mytable
GO
I get
My next value doesn’t fill in the gaps.
An identity value is strictly a “what’s the next number” process. It does nothing to manage the existing values, and it does nothing about filling in gaps. That’s important to know, and to be aware of when designing your database around identity values.
Book Review: Big Red - Voyage of a Trident Submarine
I've grown up reading Tom Clancy and probably most of you have at least seen Red October, so this book caught my eye when browsing used books for a recent trip. It's a fairly human look at what's involved in sailing on a Trident missile submarine...
2009-03-10
1,439 reads