문제

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

So both clustered index as well as non-clustered index sorts data physically as soon as it created?

As per my reading only clustered index does physically sorting?

도움이 되었습니까?

해결책

The non clustered index does not sort the data on disk like a clustered index.

But the query optimiser generates a query plan that scans this non-clustered index, which gives the data in the order of the index. This happens because the index exactly matches the table: one column in both table and index. SO it uses the index and you apparent ordering of data.

If you add more columns so that the index is useless for a full table scan, a query plan is generated that scans the actual heap data. The index is not used.

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

다른 팁

Physically, table data is arranged only by clustered index. Different indexes are used depending on query plan. In case non-clustered index is used, data is retrieved not from a table and, as a result, you see that the data is ordered.

Query Plan

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top