Does the NEWID()
function never give me the same ID as it already did? Let's say I select a NEWID()
and it returns '1' (just as an example). Will it never return '1' again? Is it impossible?
In assigning the default value of NEWID() , each new and existing row has a unique value for the CustomerID column.
Long story in short: NEWID() can generate duplicate value, however, the probability is one in a billion which is very negligible.
Use NEWID() to Create a Unique Value in SQL Server More specifically, it's an RFC4122-compliant function that creates a unique value of type uniqueidentifier. The value that NEWID() produces is a randomly generated 16-byte GUID (Globally Unique IDentifier). This is also known as a UUID (Universally Unique IDentifier).
Furthermore, the newid function generates a random GUID that comes in handy to return randomized rows from a SELECT query. The return list of a SQL select query consists of random records when we use NEWID() function in the ORDER BY clause of the query.
Both NEWID()
and NEWSEQUENTIALID()
give globally unique values of type uniqueidentifier
.
NEWID()
involves random activity, thus the next value is unpredictable, and it's slower to execute.
NEWSEQUENTIALID()
doesn't involve random activity, thus the next generated value can be predicted (not easily!) and executes faster than NEWID()
.
So, if you're not concerned about the next value being predicted (for security reasons), you can use NEWSEQUENTIALID()
. If you're concerned about predictability or you don't mind the tiny performance penalty you can use NEWID()
.
However, in strict sense, there are still negligible chances that GUIDs generated by different machines have the same value. In practice, it's considered as being impossible.
If you want further info, read this: Which method for generating GUIDs is best for ensuring the GUID is really unique?
Note NEWID()
complies RFC 4122. And the other function uses a Microsoft's algorithm for generating the value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With