[英]Why does nonclustered index column still do index scan instead of index seek
[英]In this demo,should I create a index on each column or just one Nonclustered index (Index Scan、Seek)
測試DDL:
CREATE TABLE TestTable([col1] varchar(2), [col2] varchar(2), [col3] varchar(2));
INSERT INTO TestTable ([col1], [col2], [col3]) VALUES ('a1', 'b1', 'c1');
example1(只有一個非聚集索引):
Create Nonclustered Index Index_TestTable on TestTable ([col1], [col2], [col3]) ;
select [col2], [col3] from TestTable
where [col2] = 'b1' ;
結果:
Index Scan
example2(兩個非聚集索引):
Create Nonclustered Index Index_TestTable on TestTable ([col1], [col2], [col3]) ;
Create Nonclustered Index Index_TestTable2 on TestTable ([col2], [col1], [col3]) ;
select [col2], [col3] from TestTable
where [col2] = 'b1' ;
結果:
Index Seek
問:我應該在每一列上創建一個索引還是僅創建一個索引?
PS。 select .. where col1,col2,col3
的列順序是隨機的。
如果您總是要使用col2
查詢表,那么您需要在索引中包括col1和col3,您可以為col2
創建一個索引,如下所示:
Create Nonclustered Index Index_TestTable on TestTable ([col2]) ;
您尚未提供有關為什么需要在這些列上建立索引的任何信息,但是根據一般經驗,我可以告訴您,在表的每個單列上創建索引都不是正確的方法。
非聚集索引可以提高搜索性能,但會對插入/更新/刪除操作產生負面影響(並且可能浪費存儲空間)。
如果在表中添加新的非聚集索引,則實際上會創建一個新表來維護該索引。 例如,如果您在LastName列上創建非聚集索引,則將創建一個新表來存儲LastName的排序列表以及指向相應行的指針。 如果您在LastName上搜索表,這可能會提高性能,但對表更新有負面影響,因為每次更新表時,您也需要更新/排序索引。
非聚集索引只能在您定期搜索的列上創建。
我完全同意Hooman的評論。 但是,我只想解釋一下為什么在example2中獲得Index Seek的原因,如下所示:
由於TestTable
僅包含三列,所有列均包含在非聚集索引中,因此它們在索引中的順序導致了差異。
在example2中,由於索引Index_TestTable2
具有[col2],因此僅執行一次查找(基於where [col2] = 'b1'
)。 因此,如果在example2中刪除索引Index_TestTable
,則仍應獲得“索引查找”。 請參閱此處了解更多詳細信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.