views:

49

answers:

2

Looking through a few SQL implementations, I noticed that most DBMSs support defining an index on a column with a descinding order, e.g.

CREATE INDEX anIndex ON aTable (aColumn DESC);

When would this be advantageous over an ASC index? Why is ASC or DESC part of the index definition?

If the implementation of an index is efficient (B-tree or even a binary search in a sorted list), I can't see any material difference between an ASC or DESC index.

What am I missing?

+2  A: 

If the table is clustered, the index in fact becomes this:

acolumn DESC, id ASC

and can be used in queries like

SELECT  TOP 1 *
FROM    mytable
ORDER BY
        acolumn DESC, id ASC

or

SELECT  TOP 1 *
FROM    mytable
ORDER BY
        acolumn ASC, id DESC

, but not in

SELECT  TOP 1 *
FROM    mytable
ORDER BY
        acolumn DESC, id DESC

For composite indexes, the columns can be ordered in opposite directions as well:

CREATE INDEX anIndex ON aTable (aColumn DESC, bColumn ASC);
Quassnoi
+1  A: 
  1. When you think that users need to see the data in reverse order. Sometimes an index can be used to optimize an ORDER BY.

  2. When you're trying to play tricky games with physical storage to get rows with certain properties to clump together.

S.Lott
A `B-Tree` can be traversed in both directions regardless of the comparison function.
Quassnoi
@Quassnoi: Interesting point. What does that have to do with answering *why* someone would need a reverse-order index?
S.Lott
My point was that the `DESC`-ordered query can be served with an `ASC`-ordered index just as well as with a `DESC`-ordered index. The field ordering only makes sense for composite indexes.
Quassnoi
True. The only time I'd consider creating an index on `(col1 ASC, col2 DESC)` is if the index were designed to support a business-critical query that wanted the data sorted by `col1 ASC col2 DESC`.
Adam Musch