SQLServer-何时使用群集索引与非群集索引?

我知道聚集索引和非聚集索引之间的主要区别,并且了解它们实际上是如何工作的。我了解了聚集索引和非聚集索引如何提高读性能。但有一件事我不确定是什么原因让我选择其中一个而不是另一个。

例如: 如果一个表没有聚集索引,应该创建一个非聚集索引,这样做有什么好处

101020 次浏览

I just want to put in a word of warning: please very carefully pick your clustered index! Every "regular" data table ought to have a clustered index, since having a clustered index does indeed speed up a lot of operations - yes, speed up, even inserts and deletes! But only if you pick a good clustered index.

It's the most replicated data structure in your SQL Server database. The clustering key will be part of each and every non-clustered index on your table, too.

You should use extreme care when picking a clustering key - it should be:

  • narrow (4 bytes ideal)

  • unique (it's the "row pointer" after all. If you don't make it unique SQL Server will do it for you in the background, costing you a couple of bytes for each entry times the number of rows and the number of nonclustered indices you have - this can be very costly!)

  • static (never change - if possible)

  • ideally ever-increasing so you won't end up with horrible index fragmentation (a GUID is the total opposite of a good clustering key - for that particular reason)

  • it should be non-nullable and ideally also fixed width - a varchar(250) makes a very poor clustering key

Anything else should really be second and third level of importance behind these points ....

See some of Kimberly Tripp's (The Queen of Indexing) blog posts on the topic - anything she has written in her blog is absolutely invaluable - read it, digest it - live by it!