SQL SERVER INDEX (Part 3): Concatenated Index
The most important consideration when defining a concatenated index is how to choose the column order so the index can be used as often as possible.
To demonstrate, I will use the StackOverflow2010 database. Feel free to follow along with my examples. If you haven't, please checkout Tools I Used During Query Performance Troubleshooting to see how to setup to obtain execution plan and the number of logical reads.
Let's consider two queries:
Query 1:
FROM dbo.Posts
WHERE OwnerUserId = 26837
AND PostTypeId = 2
Query 2:
FROM dbo.Posts
WHERE OwnerUserId = 26837
How do we create an index that can benefit both queries? There are two choices:
Choice 1:
ON [dbo].[Posts] ( [owneruserid], [posttypeid] )
Choice 2:
ON [dbo].[Posts]( [posttypeid], [owneruserid] )
Now, let's examine the execution plans of the two queries when one of these indexes is available.
Choice 1 (Index IX_OwnerUserID_PostTypeID):
With this index, both queries benefit, as they can perform index seeks, resulting in small number of logical reads for both.
Choice 2 (Index IX_PostTypeID_OwnerUserID):

DROP INDEX [IX_OwnerUserID_PostypeId] ON [dbo].[Posts];
Comments
Post a Comment