Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server : does NEWID() always gives a unique ID?

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?

like image 317
user2254739 Avatar asked Jul 28 '13 13:07

user2254739


People also ask

Is Newid unique in SQL Server?

In assigning the default value of NEWID() , each new and existing row has a unique value for the CustomerID column.

Can newid () be duplicate?

Long story in short: NEWID() can generate duplicate value, however, the probability is one in a billion which is very negligible.

What does newid () do?

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).

Is Newid random?

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.


1 Answers

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.

like image 190
JotaBe Avatar answered Sep 29 '22 10:09

JotaBe