When you create an index on a column or number of columns in MS SQL Server (I’m using version 2005), you can specify that the index on each column be either ascending or descending. I’m having a hard time understanding why this choice is even here. Using binary sort techniques, wouldn’t a lookup be just as fast either way? What difference does it make which order I choose?
Share
This primarily matters when used with composite indexes:
can be used for either:
or:
, but not for:
An index on a single column can be efficiently used for sorting in both ways.
See the article in my blog for details:
Update:
In fact, this can matter even for a single column index, though it’s not so obvious.
Imagine an index on a column of a clustered table:
The index on
col1keeps ordered values ofcol1along with the references to rows.Since the table is clustered, the references to rows are actually the values of the
pk. They are also ordered within each value ofcol1.This means that that leaves of the index are actually ordered on
(col1, pk), and this query:needs no sorting.
If we create the index as following:
, then the values of
col1will be sorted descending, but the values ofpkwithin each value ofcol1will be sorted ascending.This means that the following query:
can be served by
ix_mytable_col1_descbut not byix_mytable_col1.In other words, the columns that constitute a
CLUSTERED INDEXon any table are always the trailing columns of any other index on that table.