Question

I have an SQL database with a set of tables that have Unique Id's. For the longest time I have been using the unique Identifier datatype and passing in a guid from my C# interface. However for the purpose of speed when querying I have decided to switch to using a bigint and passing in a long.

Whats the easiest way to create unique longs each time I run the code so that there is no duplication of ID?

Was it helpful?

Solution

The only way you could guarantee that the bigint is unique within the database table, is to let SQL Server generate it for you - make it an IDENTITY column.

Did you actually measure performance with uniqueidentifier and found it too slow?

OTHER TIPS

If speed is an issue, you can get query improvements if using a uniqueidentifier by generating it using the newsequantialID() function rather than newID(). The new method generates sequential uniqueidentifiers

Where do you see the slowdown? Query or Insert/Update? I ask because GUID's as primary keys aren't great for insert/update because they're not sequential like IDENTITY's and can cause some thrashing in the clustered index of a key. But SQLServer has sequential-guids now that resolve that. I hear a lot about using GUID's as keys being slow but I wonder how much this is really true. Especially on 64-bit machines - is comparing 128-bit numbers really that much slower than comparing 64 or even 32 bit numbers?

There are other options for generating unique numbers besides a seed. One possibility is to generate a number based on time, something like the ticks, or better calculate the number of seconds since the start of 2009. Then append a unique digit based on the location (or account if you are not doing it on the server) the number was created to the end of the number (the least significant digit).

So if your new unique number was created on app server 1 and it's id was 42 and it's has been 4000 seconds since the start of 2009, your new identifier would be 400042. The next one generated could be 400942, and one generated from a different server at exactly the same time could be 400943.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top