Are there any differences between following two indexes?
- IDX_IndexTables_1
- IDX_IndexTables_2
If there are any, what are the differences?
create table IndexTables (
id int identity(1, 1) primary key,
val1 nvarchar(100),
val2 nvarchar(100),
)
create index IDX_IndexTables_1 on IndexTables (val1, val2)
GO
create index IDX_IndexTables_2 on IndexTables (val2, val1)
GO
Yes. There is a difference.
The composite index
IDX_IndexTables_1can be used for any query where theval1column is used in the where clause.The composite index
IDX_IndexTables_2can be used for any query where theval2column is used in the where clause.So, for instance
IDX_IndexTables_2cannot be used for this query (but IDX_IndexTables_1 can be used):but can be used for this query:
The way to think about a composite index is think about a paper telephone directory; It is indexed by the surname column, and then the firstname column: you can look up by surname but not by firstname on its own.