Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When would you define an index with a descending order?

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?

like image 371
Thorsten Avatar asked Oct 29 '25 05:10

Thorsten


1 Answers

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);
like image 52
Quassnoi Avatar answered Nov 03 '25 10:11

Quassnoi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!