I ran an execution plan recently and SSMS suggested that I add a non-clustered index to a table.
At first I added the index via the DB Diagram gui. The index that it gave me looked like this:
CREATE NONCLUSTERED INDEX [IX_MyTable] ON [dbo].[MyTable]
(
[ID_ForeignKey] ASC,
[ID] ASC
)
That was not the index that it was looking for. Next I added an index via right click in Object Explorer. I added it to the ID_Foreign key table and on the “Included Columns” page I included the ID column. The index it gave me looked like this:
CREATE NONCLUSTERED INDEX [IX_MyTable] ON [dbo].[MyTable]
(
[ID_ForeignKey] ASC
)
INCLUDE ( [ID])
That was the index it was looking for.
What’s the difference between these indexes?
The first creates an index on both columns, that is sorted by the first, and then the second column.
The second index only sorts on the first column, but also carries with it the data from the second column. This avoids needing to return to the table to get the data for that column.
The first index will require more computation on inserts and updates, so if you do not need the second column indexed, go with the second version of the index. Both will provide the data you need without having to look it up in the table.