在这里,我正在研究 SQL Server Management Studio 上的非聚集索引。
我创建了一个包含超过 100 万条记录的表。该表有一个主键。
CREATE TABLE [dbo].[Customers](
[CustomerId] [int] IDENTITY(1,1) NOT NULL,
[CustomerName] [varchar](100) NOT NULL,
[Deleted] [bit] NOT NULL,
[Active] [bit] NOT NULL,
CONSTRAINT [PK_Customers] PRIMARY KEY CLUSTERED
(
[CustomerId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
这是我将用来查看执行计划显示的查询:
SELECT CustomerName FROM Customers
好吧,在没有额外的非聚集索引的情况下执行这个命令,它会导致执行计划向我展示:
I/O cost = 3.45646
Operator cost = 4.57715
现在我正在尝试看看是否可以提高性能,所以我为这个表创建了一个非聚集索引:
1) 第一个非聚集索引
CREATE NONCLUSTERED INDEX [IX_CustomerID_CustomerName] ON [dbo].[Customers]
(
[CustomerId] ASC,
[CustomerName] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF,
IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
再次对客户表执行选择,执行计划显示:
I/O cost = 2.79942
Operator cost = 3.92001
似乎更好。现在我删除了这个刚刚创建的非聚集索引,以便创建一个新索引:
2) 第一个非聚集索引
CREATE NONCLUSTERED INDEX [IX_CustomerIDIncludeCustomerName] ON [dbo].[Customers]
(
[CustomerId] ASC
)
INCLUDE ( [CustomerName]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
使用这个新的非聚集索引,我再次执行了 select 语句,执行计划显示了相同的结果:
I/O cost = 2.79942
Operator cost = 3.92001
那么,我应该使用哪个非聚集索引?为什么 I/O 和 Operator 的执行计划成本相同?我做错了什么还是预期的?
谢谢你