Re: Index usage in order by with multiple columns in order-by-clause - Mailing list pgsql-sql

From Tom Lane
Subject Re: Index usage in order by with multiple columns in order-by-clause
Date
Msg-id 14180.1186781414@sss.pgh.pa.us
Whole thread Raw
In response to Index usage in order by with multiple columns in order-by-clause  (Andreas Joseph Krogh <andreak@officenet.no>)
Responses Re: Index usage in order by with multiple columns in order-by-clause  (Andreas Joseph Krogh <andreak@officenet.no>)
List pgsql-sql
Andreas Joseph Krogh <andreak@officenet.no> writes:
> Is there a way I can have multiple columns in the ORDER BY clause, each with
> different ASC/DESC-order and still use an index to speed up sorting?

A btree index isn't magic, it's just an ordered list of entries.  So you
can't just randomly flip the ordering of individual columns.  For
instance, the natural sort order of a 2-column index on (x,y) is like
x    y
1    11    21    32    12    22    33    13    23    3

If you scan this index forwards, you get the equivalent ofORDER BY x ASC, y ASC
If you scan it backwards, you get the equivalent ofORDER BY x DESC, y DESC
But there is no way to get the equivalent of x ASC, y DESC from
a scan of this index, nor x DESC, y ASC.

If you have a specific requirement for one of those combinations,
what you can do is build an index in which one of the columns is
"reverse sorted".  For instance, if we reverse-sort y, the index
ordering looks like
x    y
1    31    21    12    32    22    13    33    23    1

Now we can get ORDER BY x ASC, y DESC from a forwards indexscan,
or ORDER BY x DESC, y ASC from a backwards scan.  But there's no
way to get ASC/ASC or DESC/DESC from this index.  If you really need
all four orderings to be available, you're stuck with maintaining
two indexes.

Reverse-sorted index columns are possible but not well supported in
existing PG releases (you need a custom operator class, and the planner
is not all that bright about using them).  8.3 will have full support.
        regards, tom lane


pgsql-sql by date:

Previous
From: "Scott Marlowe"
Date:
Subject: Re: Race condition in resetting a sequence
Next
From: gherzig@fmed.uba.ar
Date:
Subject: foreign key pointing to diff schema?