Skip to content
Advertisement

Which is the most common ID type in SQL Server databases, and which is better?

Is it better to use a Guid (UniqueIdentifier) as your Primary/Surrogate Key column, or a serialized “identity” integer column; and why is it better? Under which circumstances would you choose one over the other?

Advertisement

Answer

I personally use INT IDENTITY for most of my primary and clustering keys.

You need to keep apart the primary key which is a logical construct – it uniquely identifies your rows, it has to be unique and stable and NOT NULL. A GUID works well for a primary key, too – since it’s guaranteed to be unique. A GUID as your primary key is a good choice if you use SQL Server replication, since in that case, you need an uniquely identifying GUID column anyway.

The clustering key in SQL Server is a physical construct is used for the physical ordering of the data, and is a lot more difficult to get right. Typically, the Queen of Indexing on SQL Server, Kimberly Tripp, also requires a good clustering key to be uniqe, stable, as narrow as possible, and ideally ever-increasing (which a INT IDENTITY is).

See her articles on indexing here:

A GUID is a really bad choice for a clustering key, since it’s wide, totally random, and thus leads to bad index fragmentation and poor performance. Also, the clustering key row(s) is also stored in each and every entry of each and every non-clustered (additional) index, so you really want to keep it small – GUID is 16 byte vs. INT is 4 byte, and with several non-clustered indices and several million rows, this makes a HUGE difference.

In SQL Server, your primary key is by default your clustering key – but it doesn’t have to be. You can easily use a GUID as your NON-Clustered primary key, and an INT IDENTITY as your clustering key – it just takes a bit of being aware of it.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement