How can a Non-Clustered index output a column that is not included in the index

放肆的年华 提交于 2019-12-19 11:45:16

问题


Viewing the Execution plan, i see "column A" in the Output List. The operation is an Index Scan on a Non-Clustered Index : "IX_name"

When i see the definition of this index. I do not see "column A" in either Index Key columns or Included columns.

How is a Non-Clustered index being used to output a column that is not present in the index. Shouldn't it use a Table Scan on the table or some other index which has "column A" present in it.


回答1:


If the table itself is clustered1, then all secondary indexes contain a copy of the clustering key2 (a key that determines the physical order of rows in the clustered table).

The reason: rows in a clustered table are physically stored within a B-tree (not table heap), and therefore can move when B-tree nodes get split or coalesced, so the secondary index cannot just contain the row "pointer" (since it would be in danger of "dangling" after the row moves).

Often, that has detrimental effect on performance3 - querying through secondary index may require double-lookup:

  • First, search the secondary index and get the clustering key.
  • Second, based on the clustering key retrieved above, search the clustered table itself (which is B-tree).

However, if all you want are the fields of the clustering key, only the first lookup is needed.


1 Aka "clustered index" under MS SQL Server.

2 Usually, but not necessarily a PRIMARY KEY under MS SQL Server.

3 It is unfortunate that clustering is on by default under MS SQL Server - people often just leave the default without fully considering its effects. When clustering is not appropriate, you should specify NONCLUSTERED keyword explicitly to turn it off.




回答2:


Internally, a non-clustered index contains all key columns of the clustered key. This is to support the key lookup operation and to ensure that internally each index row has a unique key. For heaps each NCI contains the row bookmark for the same reasons.



来源:https://stackoverflow.com/questions/23056790/how-can-a-non-clustered-index-output-a-column-that-is-not-included-in-the-index

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!