Sql-server – Adding non-nullable NEWSEQUENTIALID() column to existing table

alter-tablesql-server-2008uniqueidentifier

In SQL Server 2008, I am adding a non-nullable column to an existing table, and want to make the default NEWSEQUENTIALID().

ALTER TABLE MyTable 
ADD MyColumn UNIQUEIDENTIFIER NULL
CONSTRAINT DF_MyTable_MyColumn DEFAULT NEWSEQUENTIALID()

UPDATE MyTable SET MyColumn = NEWID()

ALTER TABLE MyTable
ALTER COLUMN MyColumn UNIQUEIDENTIFIER NOT NULL

Is it safe to populate the column with NEWID() as shown above, or is there a better way to use a sequential ID value?

My concern is that NEWID() will generate a new guid that may be close to the sequential guid. Then when the sequential guid hits that value from NEWID(), it will run into issues.

Best Answer

I tried what you are doing but unfortunately it did not give me sequential IDs. I initially tried updating with NEWSEQUENTIALID() but it isn't allowed. Try using the DEFAULT keyword instead.

UPDATE MyTable SET MyColumn = DEFAULT

Here is the test I did to confirm that the GUIDs were sequential:

CREATE TABLE MyTable (id int not null identity(1,1))
GO

INSERT INTO MyTable DEFAULT VALUES
GO 1000

ALTER TABLE MyTable 
ADD MyColumn UNIQUEIDENTIFIER NULL
CONSTRAINT DF_MyTable_MyColumn DEFAULT NEWSEQUENTIALID()
GO
UPDATE MyTable SET MyColumn = DEFAULT
GO
ALTER TABLE MyTable
ALTER COLUMN MyColumn UNIQUEIDENTIFIER NOT NULL
GO

SELECT * FROM MyTable ORDER BY MyColumn 

I did a quick scan of the results and my id column was all in numeric order.