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

2020-02-27 03:24发布

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?

3条回答
啃猪蹄的小仙女
2楼-- · 2020-02-27 04:09

I had the same question, so I ran this simple query to see how unique the newid () could be, as you'll see there is no repeated IDs even in the same milisecond:

DECLARE @TRIES BIGINT, @ID UNIQUEIDENTIFIER, @REPEATED_ID UNIQUEIDENTIFIER
SET @TRIES = 1
SET @REPEATED_ID=NEWID()
WHILE @TRIES <= 1000
BEGIN
    SET @ID=NEWID() 
    IF @REPEATED_ID=@ID
        PRINT 'SAME -> ID '+CONVERT(NVARCHAR(MAX),@TRIES)+': '+ CONVERT(CHAR(36),@ID)
    ELSE
        PRINT 'DISTINCT -> ID '+CONVERT(NVARCHAR(MAX),@TRIES)+': '+ CONVERT(CHAR(36),@ID) + ' AT ' + CONVERT(VARCHAR,CAST(GETDATE() AS DATETIME2(3)) 
)
    SET @TRIES += 1
    SET @REPEATED_ID=@ID
END

You can define @TRIES as you wish.

查看更多
放荡不羁爱自由
3楼-- · 2020-02-27 04:19

If you're running NEWID() on the same machine then the return value will always be unique because it incorporates the current time stamp in its calculation.

On separate machines/systems, however, you could technically get the same id but the probability of that happening is so low that today's SQL DB community has essentially accepted that it IS impossible. Microsoft has more or less banked their reputation on it.

Related

查看更多
趁早两清
4楼-- · 2020-02-27 04:24

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.

查看更多
登录 后发表回答