复合索引和锁定

Composite index and locking

我正在尝试最大程度地减少在可序列化事务期间锁定的行数。

似乎是问题的查询是:

UPDATE CLIENTS 
SET SOMEVALUE = 'A' 
WHERE CLIENT_ID = 'aaaa' AND YEAR = 2015

目前没有索引,主键除外。

使用 CLIENT_IDYEAR 创建复合索引(非唯一)是否有助于键范围锁定?

编辑:在范围键示例之后添加了额外的资源link。

添加索引不一定有帮助。在走那条路之前,我会首先捕获您的查询的实际执行计划并保存。接下来,为您的 2 个谓词 CLIENT_ID 和 YEAR 创建统计信息。 运行 查询再次捕获新的查询计划并比较 2。

下面是一个示例,说明如何创建统计信息、查看新统计信息以及查看统计信息的密度(唯一性)和直方图(关键列的频率)。

拥有正确的统计数据确实可以减少返回记录的数量。

使用 AdventureWorks2014 的示例:

--Create statistics for the 2 predicates
CREATE STATISTICS PersonType_EmailPromotion ON Person.Person (PersonType, EmailPromotion)

--View your newly created statistic
exec sp_helpstats 'Person.Person', 'ALL'

--See the density and histogram for you statistic
dbcc show_statistics('Person.Person', PersonType_EmailPromotion)

结果 dbcc show_statistics

--Notice the uniqueness of PersonType and EmailPromotion compared to PersonType alone.
All density Average Length  Columns
0.1666667   4               PersonType
0.05555556  8               PersonType, EmailPromotion

/*
  This shows the number of rows between PersonType range keys. 
  Notice in, 18329 rows between GC and IN, this is where having 
  2 column statistics really helps narrow down the ranges.
*/
RANGE_HI_KEY    RANGE_ROWS  EQ_ROWS     DISTINCT_RANGE_ROWS AVG_RANGE_ROWS
EM              0           297.2556    0                   1
GC              0           395.5958    0                   1
IN              0           18329.27    0                   1
SC              0           688.3814    0                   1
SP              0           37.99508    0                   1
VC              0           223.5004    0                   1

有关 dbcc show_statistics and multi-column statistics 的信息。

希望对您有所帮助!

如果最终在查询中使用索引,则索引将有助于锁定键范围。然后,它可以帮助减少数据量 SQL 服务器需要接触并因此锁定。

添加索引并比较前后的实际执行计划。大多数情况下,您应该在这种情况下进行正常的索引调整。