如果禁用非聚集索引,统计信息是否仍然使用?

Cha*_*win 11 index sql-server sql-server-2017

tl;dr - 正如标题所述 - 如果我禁用表上的非聚集索引,是否仍使用该索引的链接统计信息?


我知道有很多关于“删除与禁用索引”的问题......但我找不到专门涵盖统计数据的问题。

我知道统计数据没有改变或改变(至少这是我从 MS 文档中收集到的)。但我的问题是统计数据是否仍然被使用


作为背景,我正在开展一个大型索引调整项目。它涉及在数百个相同的数据库中添加/删除索引,但工作负载模式各不相同。总共有超过 200 万个索引。

我的第一步是删除所有“未使用”的索引。然而,我并没有放弃它们,而是考虑禁用它们,以便保留定义。这将允许我在表中记录任何禁用索引的实例、数据库、对象 ID 和索引名称/ID。如果此后性能开始下降,可以重新启用(重建)索引。

但是,如果已禁用索引的统计信息仍用于生成计划...那么禁用它们不会产生与删除它们相同的性能影响。如果是这种情况,那么禁用索引并不是“真正的”性能影响测试,如果禁用的索引最终被删除,我可能会面临引入性能问题的风险。

Zik*_*ato 20

是的,即使索引被禁用,优化器仍然使用统计信息。

对于演示,我使用AdventureWorks2019 OLTP和文档中的查询示例

我将使用实际执行计划运行此查询

SELECT P.Weight AS Weight, S.Name AS BikeName
FROM Production.Product AS P
    JOIN Production.ProductSubcategory AS S
    ON P.ProductSubcategoryID = S.ProductSubcategoryID
WHERE P.ProductSubcategoryID IN (1,2,3) AND P.Weight > 25
ORDER BY P.Weight;
Run Code Online (Sandbox Code Playgroud)

如果我打开执行计划 XML,我可以看到正在使用的统计信息(为了简洁起见,我删除了一些属性)。

<OptimizerStatsUsage>
  <StatisticsInfo Table="[Product]" Statistics="[AK_Product_rowguid]" />
  <StatisticsInfo Table="[Product]" Statistics="[AK_Product_ProductNumber]" />
  <StatisticsInfo Table="[Product]" Statistics="[AK_Product_Name]" />
  <StatisticsInfo Table="[Product]" Statistics="[_WA_Sys_00000013_1CBC4616]" />
  <StatisticsInfo Table="[Product]" Statistics="[_WA_Sys_0000000E_1CBC4616]" />
  <StatisticsInfo Table="[ProductSubcategory]" Statistics="[PK_ProductSubcategory_ProductSubcategoryID]" />
</OptimizerStatsUsage>
Run Code Online (Sandbox Code Playgroud)

我将根据示例创建推荐的统计信息并重新运行查询

CREATE STATISTICS BikeWeights
    ON Production.Product (Weight)
WHERE ProductSubcategoryID IN (1,2,3);
Run Code Online (Sandbox Code Playgroud)

在顶部,我们可以在显示计划 XML 中看到统计信息的名称。 在此输入图像描述

我将删除统计信息并创建一个具有相同定义的过滤的非聚集索引(这也创建了统计信息)

DROP STATISTICS Production.Product.BikeWeights

CREATE INDEX IX_Product_BikeWeights ON Production.Product
(Weight) WHERE ProductSubcategoryID IN (1, 2, 3)
Run Code Online (Sandbox Code Playgroud)

我们可以使用此 DMO 查询检查索引和统计信息:


SELECT 
    i.name
    , i.index_id
    , i.is_disabled
    , s.stats_id
    , s.has_filter
    , s.user_created
    , s.auto_created
FROM sys.indexes AS i
JOIN sys.stats AS s
    ON s.object_id = i.object_id
    AND s.stats_id = i.index_id
WHERE 
    i.object_id = OBJECT_ID('Production.Product')
    AND i.name = 'IX_Product_BikeWeights'
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

请注意,sys.statsDMV 没有is_disabled

重新运行查询显示,名为的统计数据从BikeWeights更改为IX_Product_BikeWeights

在此输入图像描述

现在,我将禁用索引并重新运行 DMO 和测试查询。

ALTER INDEX IX_Product_BikeWeights ON Production.Product DISABLE
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

在此输入图像描述

即使索引被禁用,统计信息仍在使用。

对于最终运行,让我们删除索引(这也会删除统计信息)

DROP INDEX IX_Product_BikeWeights ON Production.Product
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

统计数据也缺失。