SQL SERVER – COUNT(*) and Index Used – Part 2

Yesterday I wrote a blog post on the topic SQL SERVER – COUNT(*) and Index Used, lots of people asked me to follow up question. The most question was around what would happen if there was a heap or only clustered index. Well, let us check that out in today’s blog post.

SQL SERVER - COUNT(*) and Index Used - Part 2 indexused-800x238

First, let us create a sample table. I am creating the table based on the Person.Address table of AdventureWorks database.

INTO TestTable
FROM [AdventureWorks].[Person].[Address]

Please note that the table has currently no index at all. Now let us enable the execution plan.

Now run the following script to count the number of rows.

FROM TestTable

Now check the execution plan. In the plan, you will see Table Scan.

SQL SERVER - COUNT(*) and Index Used - Part 2 indexused1

Next, we will create clustered index on the table.

([AddressID] ASC)

Now once again run the command to count the number of rows and check the execution plan.

Here you will see Clustered Index Scan in an execution plan. This is because once you have clustered index, you will not have a table scan. I have often discussed this during Comprehensive Database Performance Health Check.

SQL SERVER - COUNT(*) and Index Used - Part 2 indexused2

The next step is to create a nonclustered index and check the execution plan.

([StateProvinceID] ASC)

In the execution plan, you will notice NonClustered Index Scan because that is created on a narrow column. Please understand that SQL Server Optimization Engine always builds the execution plan which is the most effective and efficient.

SQL SERVER - COUNT(*) and Index Used - Part 2 indexused3

A nonclustered index with less number of column is always more efficient in the COUNT(*) operations.

Once you are done with the test experiment you can run the following command to drop the table.


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.

Reference: Pinal Dave (http://blog.SQLAuthority.com)

Clustered Index, Execution Plan, SQL Index, SQL Scripts, SQL Server
Previous Post
MS Access – Count Distinct Values
Next Post
COUNT(*) and Index Frequently Asked Questions

Related Posts

Leave a Reply