创建索引SQL Server 2008

Bil*_*lla 6 sql sql-server sql-server-2008 sql-server-2012

最近我被用于数据库微调.我有一些关于SQL Server的想法,并决定创建一些索引.

提到这个http://sqlserverplanet.com/ddl/create-index

但我不明白其他类型的索引如何INCLUDE,WITH选项将有所帮助.我试过谷歌,但没有看到一个简单的描述何时使用它们.

CREATE NONCLUSTERED INDEX IX_NC_PresidentNumber
ON dbo.Presidents (PresidentNumber)
INCLUDE (President,YearsInOffice,RatingPoints)
WHERE ElectoralVotes IS NOT NULL

CREATE NONCLUSTERED INDEX IX_NC_PresidentNumber
ON dbo.Presidents (PresidentNumber)
WITH ( DATA_COMPRESSION = ROW )

CREATE NONCLUSTERED INDEX IX_NC_PresidentNumber
ON dbo.Presidents (PresidentNumber)
WITH ( DATA_COMPRESSION = PAGE )
Run Code Online (Sandbox Code Playgroud)

我应该使用以上哪种情况?他们会提高性能吗?

Bla*_*ICE 2

我无法谈论 with datacompression 选项,但 Include 选项绝对可以提高性能。如果您仅选择 PresidentNumber 以及 President、YearsInOffice 或 RatingPoints 列中的一个或多个,并且 ElectoralVotes 不为空,则您的查询将从索引本身获取值,而不必接触基础表。如果您的表有其他列,并且您在查询中包含其中一列,那么它将必须从表和索引中检索值。


Select top 20 PresidentNumber, President, YearsInOffice, RatingPoints
From Presidents
where ElectoralVotes IS NOT NULL
Run Code Online (Sandbox Code Playgroud)

上面的查询将仅从 IX_NC_PresidentNumber 读取,而不必从 Presidents 表中提取数据,因为查询中的所有列都包含在索引中

Select top 20 PresidentNumber, President, YearsInOffice, PoliticalParty
From Presidents
where ElectoralVotes IS NOT NULL
Run Code Online (Sandbox Code Playgroud)

此查询还将使用索引 IX_NC_PresidentNumber 和 Presidents 表,因为查询中的PoliticalParty 列不包含在索引中。

Select PresidentNumber, President, YearsInOffice, RatingPoints
From Presidents
Where RatingPoints > 50
Run Code Online (Sandbox Code Playgroud)

该查询很可能最终会进行表扫描,因为查询中的 where 子句与索引中使用的 where 子句不匹配,并且行数没有限制。