SQL SERVER – Index Scans are Not Always Bad

Are Index Scans Bad? The answer No. Index Scans are Not Always Bad. This was in-depth discussed with my client during the Comprehensive Database Performance Health Check. Let us learn about it today.

Illustrated cover: Scans Are Not Always Bad

Myth – Index Scans Bad

Lots of people think that seeks are better and scans are bad but the truth is both of them are needed when they are needed. Additionally, when people see an index scan they think that the entire table or index is scanned, well that is not true as well.

Today, let us see a simple script that demonstrates that even though the execution plan shows Index Scan, it is not giving accessing the entire table.

SET STATISTICS IO ON
SELECT TOP 1 i.InvoiceID, i.BillToCustomerID, i.Comments
FROM [WideWorldImporters].[Sales].[Invoices] i

As a matter of fact, when seeing the execution plan, we can see that it is only retrieving a single row. Let us check the output of the STATISTICS IO, it is clear from it that they are reading very little data from the table.

Execution Plan for SELECT 1.0 Rows.

Table ‘Invoices’. Scan count 1, logical reads 3, physical reads 0

Now if you think it is because of the TOP operator, well, it is not true. Here is another query where I am getting the same result but this time entire table is scanned and also STATISTICS IO shows a huge amount of rows.

SET STATISTICS IO ON
SELECT TOP 1 i.InvoiceID, i.BillToCustomerID, i.Comments
FROM [WideWorldImporters].[Sales].[Invoices] i
ORDER BY [OrderID], [Comments]

So essentially, the moral of the story is – Scans are not always bad.

Database query window.

Table ‘Invoices’. Scan count 17, logical reads 11994, physical reads 0
Table ‘Worktable’. Scan count 0, logical reads 0

Well, that’s it for today. If you liked this video, please do not forget to subscribe to my YouTube Channel – SQL in Sixty Seconds.

Here are my few recent videos and I would like to know what is your feedback about them.

Want to try this yourself? Here is how to install WideWorldImporters.

Published by Pinal Dave on SQLAuthority. More of my work at pinaldave.com.


Discover more from SQL Authority with Pinal Dave

Subscribe to get the latest posts sent to your email.

Execution Plan, SQL Index, SQL Scripts, SQL Server
Previous Post
Table Variables and Parallelism: Reads Yes, Inserts No
Next Post
Index Used for COUNT(*): SQL Server Scans the Narrowest One

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.