Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How SQL Server creates uniqueidentifier using NEWID()

Tags:

sql-server

I have a user_info table in five different locations. Now I need to integrate all the rows into a central user_info table. To do this I need a unique id for each row in source tables. Because when all the rows come into the central table, then each user must have a unique ID.

Now my questions are:

  1. if I use uniqueidentifier NEWID() for each source table then is it will be unique for globally & life time or have any chance to be duplicate?

  2. How does SQL Server create the NEWID()? I need to know the key generation structure.

like image 479
riad Avatar asked Sep 23 '12 06:09

riad


People also ask

Is Uniqueidentifier auto generated?

Yes, there are a number of ways you can auto-generate key values for your tables. The most common ways are via the use of the IDENTITY column property or by specifying a uniqueidentifier (GUID) data type along with defaulting with either the NEWID() or NEWSEQUENTIALID() function.

How do I create a Uniqueidentifier in SQL?

-- If you want to generate a new Guid (uniqueidentifier) in SQL server the you can simply use the NEWID() function. -- This will return a new random uniqueidentifier e.g. You can directly use this with INSERT statement to insert new row in table.


1 Answers

Yes, there is no chance of a duplicate between machines.

NEWID() is based on a combination of a pseudo random number (from the clock) and the MAC address of the primary NIC.

However, inserting random numbers like this as the clustered key on a table is terrible for performance. You should consider either NEWSEQUENTIALID() or a COMB-type function for generating GUIDs that still offer the collision-avoidance benefits of NEWID() while still maintaining acceptable INSERT performance.

like image 60
richardtallent Avatar answered Oct 26 '22 07:10

richardtallent