Clustered也会对物理数据和非聚集索引进行排序?

Reg*_*ser 2 sql sql-server indexing clustered-index non-clustered-index

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
Run Code Online (Sandbox Code Playgroud)

因此,聚簇索引和非聚簇索引一旦创建,就会在物理上对数据进行排序吗?

根据我的阅读,只有聚集索引进行物理排序?

gbn*_*gbn 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
Run Code Online (Sandbox Code Playgroud)