简体   繁体   English

为什么 SQL Server 中非聚集索引和聚集索引的执行计划存在差异?

[英]Why the differences in execution plan between nonclustered and clustered index in SQL Server?

Please explain why the below differences between non clustered and clustered index.请解释为什么非聚集索引和聚集索引之间存在以下差异。 First I am running the below two select statements.首先,我正在运行以下两个选择语句。

select * 
from [dbo].[index_test2]  
where id = 1 -- Nonclustered index  on id column

select * 
from [dbo].[index_test1] 
where id = 1  -- Clustered index on id column

Execution plan shows "Table scan" for the first query and "Clustered index seek (clustered)" for the second query.执行计划显示第一个查询的“表扫描”和第二个查询的“聚集索引查找(聚集)”。

Then I am running below two statements.然后我在两个语句下运行。

select id 
from [dbo].[index_test2]  
where id = 1 -- Nonclustered index  on id column

select id 
from [dbo].[index_test1] 
where id = 1  -- Clustered index on id column

Execution plan shows "Index seek (NonClustered)" for the first query and "Clustered index seek (Clustered)" for the second query.执行计划显示第一个查询的“索引查找(非集群)”和第二个查询的“集群索引查找(集群)”。

You can see from the above two cases, when using clustered index it is going for "Index seek" but for in case of NonClustered index it shows "Table scan" (executed with *) and it shows "Index seek (NonClustered)" (executing with index applied column-id).从以上两种情况可以看出,当使用聚集索引时,它会进行“索引查找”,但对于非聚集索引,它显示“表扫描”(用 * 执行)并显示“索引查找(非聚集)”(使用索引应用的 column-id 执行)。

Can any one clarify why the NonClustered index reacting differently on both cases?任何人都可以澄清为什么 NonClustered 索引对两种情况的反应不同?

A clustered index defines the order in which data is physically stored in a table but A non-clustered index doesn't sort the physical data inside the table.In fact, a non-clustered index is stored at one place and table data is stored in another place.聚集索引定义了数据在表中物理存储的顺序,但非聚集索引不对表内部的物理数据进行排序。实际上,非聚集索引存储在一个地方,而存储表数据在另一个地方。

If you use an Non-Clustered Index it works in Index seek (NonClustered) mode when you call it property,but If you put where in Non-Clustered Index mode but call in select more expressions that are not Cover index change mode to Table scan如果您使用Non-Clustered Index则在调用属性时它会在Index seek (NonClustered) Non-Clustered Index Index seek (NonClustered)模式下工作,但是如果您将where置于Non-Clustered Index模式中,但调用select更多不是覆盖索引更改模式的表达式到Table scan

Indexes with included columns provide the greatest benefit when covering the query.包含列的索引在覆盖查询时提供最大的好处。 This means that the index includes all columns referenced by your query, as you can add columns with data types, number or size not allowed as index key columns这意味着索引包括查询引用的所有列,因为您可以添加数据类型、数量或大小不允许作为索引键列的列

But in Clustered Index , since the actual sorting is done by it, you do both in Clustered index seek (clustered) mode.但是在Clustered Index ,由于实际排序是由它完成的,因此您可以在Clustered index seek (clustered)模式下进行这两种操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM