Received: from localhost (maia-1.hub.org [200.46.204.191]) by postgresql.org (Postfix) with ESMTP id 1B9229F97BD for ; Fri, 10 Aug 2007 18:30:26 -0300 (ADT) Received: from postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.204.191]) (amavisd-maia, port 10024) with ESMTP id 90706-01 for ; Fri, 10 Aug 2007 18:30:22 -0300 (ADT) X-Greylist: from auto-whitelisted by SQLgrey-1.7.5 Received: from sss.pgh.pa.us (sss.pgh.pa.us [66.207.139.130]) by postgresql.org (Postfix) with ESMTP id 278909F97AE for ; Fri, 10 Aug 2007 18:30:22 -0300 (ADT) Received: from sss2.sss.pgh.pa.us (tgl@localhost [127.0.0.1]) by sss.pgh.pa.us (8.14.1/8.14.1) with ESMTP id l7ALUEf9014181; Fri, 10 Aug 2007 17:30:14 -0400 (EDT) To: Andreas Joseph Krogh cc: pgsql-sql@postgresql.org Subject: Re: Index usage in order by with multiple columns in order-by-clause In-reply-to: <200708101653.13011.andreak@officenet.no> References: <200708101653.13011.andreak@officenet.no> Comments: In-reply-to Andreas Joseph Krogh message dated "Fri, 10 Aug 2007 16:53:12 +0200" Date: Fri, 10 Aug 2007 17:30:14 -0400 Message-ID: <14180.1186781414@sss.pgh.pa.us> From: Tom Lane X-Virus-Scanned: Maia Mailguard 1.0.1 X-Archive-Number: 200708/86 X-Sequence-Number: 29024 Andreas Joseph Krogh 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 1 1 2 1 3 2 1 2 2 2 3 3 1 3 2 3 3 If you scan this index forwards, you get the equivalent of ORDER BY x ASC, y ASC If you scan it backwards, you get the equivalent of ORDER 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 3 1 2 1 1 2 3 2 2 2 1 3 3 3 2 3 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