Reputation: 603
I created a table to test the amount of logical blocks that are being read and the execution plan chosen by the query optimizer, comparing the queries when this table has index and when it hasn't.
the test table is
create table scan
(
id int identity(1, 1),
a varchar(10),
b varchar(10),
c varchar(10),
d varchar(10),
e varchar(10),
f varchar(10)
)
When I run of of these queries:
select * from scan
select id from scan
I got 88 and 58 logical reads, and a table scan algorithm
Then I alter the table putting the pk constraint and his clustered id
alter table scan
add constraint fk_id primary key (id)
then a run the same queries:
select * from scan
select id from scan
and I got 90 and 60 scan reads and the index scan algorithm
The question is: if the query optimizer choose the best way to run the query, why it is choosing the index scan if the table scan can read less block?
Upvotes: 1
Views: 681
Reputation: 7722
When you created the primary key constraint, it was made clustered by default. This means that the heap you had previously has been ordered by this key (id
, in your case).
Data in tables can be stored in either one of two ways: either heaps or clustered indices. When the latter is created, the former is gone. So it is impossible for SQL Server to perform table scan on index - it can only be an index scan (clustered index scan, btw - this is important).
I know it may sound confusing, but try to read some basics on clustered indices - it might help.
Upvotes: 3