原文地址:
Stairway to SQL Server Indexes: Level 5, Included Columns
本文是SQL Server索引进阶系列(Stairway to SQL Server Indexes)的一部分。
之前的文章介绍了聚集索引和非聚集索引,包含下面几条很重要的内容:
上面的8行结果,是在39行ProductID=888的基础上聚合而成的。在每次查询之前都需要做一些事前工作,还需要打开IO统计,SET STATISTICS IO ON.
IF EXISTS ( SELECT 1
FROM sys.indexes
WHERE name = 'FK_ProductID_ModifiedDate'
AND OBJECT_ID = OBJECT_ID('Sales.SalesOrderDetail') )
DROP INDEX Sales.SalesOrderDetail.FK_ProductID_ModifiedDate ;
GO
--RUN 1: Execute Listing 5.2 here (no non-clustered index)
CREATE NONCLUSTERED INDEX FK_ProductID_ModifiedDate
ON Sales.SalesOrderDetail (ProductID, ModifiedDate) ;
--RUN 2: Re-execute Listing 5.2 here (non-clustered index with no include)
IF EXISTS ( SELECT 1
FROM sys.indexes
WHERE name = 'FK_ProductID_ModifiedDate'
AND OBJECT_ID = OBJECT_ID('Sales.SalesOrderDetail') )
DROP INDEX Sales.SalesOrderDetail.FK_ProductID_ModifiedDate ;
GO
CREATE NONCLUSTERED INDEX FK_ProductID_ModifiedDate
ON Sales.SalesOrderDetail (ProductID, ModifiedDate)
INCLUDE (OrderQty, UnitPrice, LineTotal) ;
--RUN 3: Re-execute Listing 5.2 here (non-clustered index with include)
三次查询的统计结果如下:
Run 1:
No Nonclustered Index
Table 'SalesOrderDetail'. Scan count 1, logical reads 1238.
Non read activity: 8%.
Run 2:
Index – No Included Columns
Table 'SalesOrderDetail'. Scan count 1, logical reads 131.
Non read activity: 0%.
Run 3:
With Included Columns
Table 'SalesOrderDetail'. Scan count 1, logical reads 3.
Non read activity: 1%.
从上面的结果可以看出:
(164 row(s) affected)
where子句过滤到1492条满足条件的数据,分组之后产生164行结果。
查询的统计如下
Run 1:
No Nonclustered Index
Table 'SalesOrderDetail'. Scan count 1, logical reads 1238.
Non read activity: 10%.
Run 2:
With Index – No Included Columns
Table 'SalesOrderDetail'. Scan count 1, logical reads 1238.
Non read activity: 10%.
Run 3:
With Included Columns
Table 'SalesOrderDetail'. Scan count 1, logical reads 761.
Non read activity: 8%.
第一次和第二次查询的执行计划是相同的,都是全表扫描。具体原因在第四级中已经介绍过,where子句没有从非聚集索引中受益。同样的,每一组在表中都很分散,读取表的时候,需要读取每一行来查看匹配的组,这些操作会消耗处理器时间和内存。
第三次查询在索引中发现了所需要的全部信息,但是不想第一个查询,发现在索引中的行,不是连续的。
扫描索引,而不是扫描表,有两个好处: