简体   繁体   中英

When using NEWSEQUENTIALID() as primary key, what should be my clustered index?

I'm using newsequentialid to generate GUIDs for my primary key in a table.

According to the documentation ( https://docs.microsoft.com/en-us/sql/t-sql/functions/newsequentialid-transact-sql?view=sql-server-ver15 ), Sequential GUIDs aren't guarantined to be generated in order.

After restarting Windows, the GUID can start again from a lower range, but is still globally unique

Basically, they're in order until you reboot the machine.

For autoincrement primary key, it makes sense for it to be the clustered index cause it's guaranteed an inserted row will be at the end.

For a GUID primary key, it doesn't make sense for it to be the clustered index cause it's random it's unlikely an inserted row will be at the end.

What about for a sequential GUID primary key? Should the primary key be the clustered index or should I try to find another column like a DateCreated field? The problem is fields like DateCreated isn't going to be a unique field. If I don't have any fields that are unique fields, what should I make as the clustered index?

Sequential GUIDs are much safer for clustered indexes than non-sequential GUIDs. In general, databases are not restarted particularly often. It is true that restarting can result in page splits and fragmentation, but that is usually not too big a consideration because restarting is rare.

That said, the primary key does not need to be the clustered index key. You can have an identity column or creation date/time as the clustered index, pretty much eliminating this issue.

I wrote a long post about this a while ago. The TL/DR is that using a sequential GUID as a clustered index key is fine. The GUIDs are actually inserted in the middle of the index, but having a small number (here one) mid-index insertion point does not cause expensive page splits or lead to harmful fragmentation.

Good Page Splits and Sequential GUID Key Generation

This same behavior applies to using a compound key as clustered index, where the leading key column has lower cardinality. Eg (CustomerId,TransactionId). Each CustomerId will have a half-full page with space for the next TransactionId, and when that page fills a new one is allocated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM