Logo Questions Linux Laravel Mysql Ubuntu Git Menu

C# generate Guid that is unique(does not exist in a table in the database)

I have a table where the primary key is of type Guid. In my MVC application, I want to add a record to this table. I know of the Guid.newGuid() that creates a new Guid. This workds well but I have a concern. How does one ensures that the created Guid is unique (does not yet exist in the database)? Is there a way to generate it by comparing already existing values to make sure that the new guid is unique across the database records?

like image 964
jpo Avatar asked Mar 24 '23 04:03


2 Answers

The entire purpose of the guid generation technique is that it doesn't need to. The algorithm will generate a globally unique value even if it doesn't have access to all of the other previously generated GUIDs.

In particular, the algorithm is to just generate one big random number. There are so many bits of data in the GUID that the odds of two of them having the same value are infinitesimally small. Small enough that they truly can be ignored.

For a more detailed analysis see Eric Lippert's blog on the subject. (In particular part three.)

Note that, as a consequence of this, using a GUID as a unique identifier will take up quite a bit more space in the database then just using a numeric identifier. Any decent database will have a special column type specifically designed to be a unique identifier that it will populate; such a column will be able to ensure uniqueness while using quite a lot less space than a GUID.

like image 117
Servy Avatar answered Apr 14 '23 19:04


The possibility od generating a duplicate is very low. However you could enforce a UNIQUE constraint on the database table.

like image 41
Darren Avatar answered Apr 14 '23 18:04