2
CREATE table comp_tb 
(
a tinyint 
) 


insert into comp_tb values('4') 
insert into comp_tb values('1') 
insert into comp_tb values('5') 
insert into comp_tb values('6') 
insert into comp_tb values('10') 
insert into comp_tb values('3') 
insert into comp_tb values('2') 
insert into comp_tb values('8') 


SELECT * from comp_tb ct --as order of insert 

create NONCLUSTERED INDEX NCI_a ON comp_tb(a) 

SELECT * from comp_tb ct --sorts in acending order 

drop INDEX NCI_a ON comp_tb 

create CLUSTERED INDEX CI_a ON comp_tb(a) 

SELECT * from comp_tb ct -- sorts in acending order 

drop INDEX CI_a ON comp_tb 

因此聚集索引和非聚集索引都會在物理創建後立即對數據進行排序?羣集對物理和非聚集索引的數據進行排序嗎?

根據我的閱讀只有聚集索引物理排序?

回答

9

非聚簇索引不像聚簇索引那樣對磁盤上的數據進行排序。

但查詢優化器生成一個查詢計劃,該計劃掃描此非聚集索引,該索引按索引的順序提供數據。發生這種情況是因爲索引與表格完全匹配:表格和索引中的一列。所以它使用索引和你明顯的數據排序。

如果添加更多列以使索引對全表掃描無用,將生成一個查詢計劃以掃描實際的堆數據。該索引未被使用。

CREATE table #comp_tb 
(
a tinyint, 
payload1 char(3000) NOT NULL, 
payload2 varchar(100) NOT NULL, 
) 

insert into #comp_tb values('4', '4' /*padded*/, '44444444444') 
insert into #comp_tb values('1', '1' /*padded*/, '1111111111111111111111111111') 
insert into #comp_tb values('5', '5' /*padded*/, '55') 
insert into #comp_tb values('6', '6' /*padded*/, '666666666666666666666666666666666666') 
insert into #comp_tb values('10', '10' /*padded*/, 'a') 
insert into #comp_tb values('3', '3' /*padded*/, '3333333') 
insert into #comp_tb values('2', '2' /*padded*/, REPLICATE('2', 50)) 
insert into #comp_tb values('8', '8' /*padded*/, '8888888888888888888888') 

SELECT * from #comp_tb ct --as order of insert 

create NONCLUSTERED INDEX NCI_a ON #comp_tb(a DESC) 

SELECT * from #comp_tb ct --as order of insert 

drop INDEX NCI_a ON #comp_tb 
+1

+1 - 真的很酷的答案。 – Devart

+0

@gbn的確太棒了。 –

2

物理上,表格數據僅由聚簇索引排列。根據查詢計劃使用不同的索引。在使用非聚集索引的情況下,不是從表中檢索數據,因此可以看到數據是有序的。

Query Plan

相關問題