Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a index seek becomes more expensive than an index scan

Tags:

sql-server

I have a basic question about Index Scan/Seek. Index scan is effective when there are large number of rows to be fetched. That is index scan cost is inversely proportional to the number of rows returned. That is less the number of rows more expensive the query becomes as it has to scan all the pages which results in more IO.

I have searched the reason why seeks become more expensive than scans but I am not able to get the reason why seek becomes expensive.

What I am confused is with Index seek. Why index seek becomes expensive with more number of rows returned. Index seek will always be faster and efficient than scans as it directly touches the pages that contain the rows. So even with large number of rows returned index seek should always be efficent than Index scan. But this does not happen. I want to know exactly why at some point seek becomes expensive.

select id,name,col1,col2
from TableA   -- Will result in index scan. Table has 10000 rows with clustered index on ID column. Query has covering index.

select id,name,col1,col2
where ID between 1 and 10
from TableA   -- Optimizer Will use index Seek.

Now why does the below query becomes expensive when index seek is forced upon -

select id,name,col1,col2
from TableA with (forceseek)
like image 636
sam Avatar asked Oct 18 '22 14:10

sam


1 Answers

The reason why Clustered index Seek is expensive than Index scan is because Index seek starts reading the B tree right from Root nodes to Leaf nodes. This involves reading the index and pages inside the Leaf nodes. Hence results in more IO. So when selectivity is less optimizer chooses index scan instead of Index seek. Seek is better only when records returned are not more than 2 to 3%.

like image 92
sam Avatar answered Nov 15 '22 06:11

sam