Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server newID - how is it created?

Tags:

sql

sql-server

I would like to use newId to generate random numbers. Usually you would use it just once, but I might be generating up to 10 random numbers per newId.

Is it random enough?

like image 815
jakub.deka Avatar asked Aug 24 '26 11:08

jakub.deka


1 Answers

Usually you would use it just once, but I might be generating up to 10 random numbers per newId. Is it random enough?

It depends on how you extract the numbers from the newid. You cannot treat it as 128 independently random bits.

For example if you use the first 8 bits for generating one random number between 0 and 255, use the next 8 bits to generate another number, etc. then you will see that your numbers will not be uniformly random.

              v

E058D654-35A8-47F2-AE40-1C4EEBBDC549
01461481-ED8D-4B85-90FA-C08621D98DAE
AE861E4E-3469-4BDB-A38B-0031DACC8DAE
AF8905D0-E41B-4300-94F2-33BB45698CD1
003308A6-AE0A-4E20-9F24-047A6955E748
76F9B7ED-79AB-4EB1-B361-8C0AF5177CE3
B8F1CAC0-591D-436B-BB21-FAAD9EECA983
7FBEAEFD-2163-4315-A783-8106909E47D8
85E2FC60-E7B3-400F-B20A-CEFBECAEE4F9
17ED0A03-ADAD-4521-97EE-04815A867B32

              ^
              |
              always 4

You should also try to avoid reusing the same bits to generate different random numbers as your numbers will become related. If in doubt, don't reuse the same number.

Note that there is also a RAND function which you can call. This returns numbers from a uniform distribution.

like image 56
Mark Byers Avatar answered Aug 27 '26 00:08

Mark Byers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!