Are there any differences between following two indexes?
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_1
can be used for any query where the val1
column is used in the where clause.
The composite index IDX_IndexTables_2
can be used for any query where the val2
column is used in the where clause.
So, for instance IDX_IndexTables_2
cannot be used for this query (but IDX_IndexTables_1 can be used):
SELECT val1, val2 FROM IndexTables
WHERE val1 = some_value
but can be used for this query:
SELECT val1, val2 FROM IndexTables
WHERE val2 = some_value AND val1 = some_other-value
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.