Index usage in order by with multiple columns in order-by-clause

From: Andreas Joseph Krogh <andreak(at)officenet(dot)no>
To: pgsql-sql(at)postgresql(dot)org
Subject: Index usage in order by with multiple columns in order-by-clause
Date: 2007-08-10 14:53:12
Message-ID: 200708101653.13011.andreak@officenet.no
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

I have the following test-case:

CREATE TABLE test(
name varchar PRIMARY KEY,
value varchar NOT NULL,
created timestamp not null
);

create index test_lowernamevalue_idx ON test ((lower(name) || lower(value)));
create index test_lowernamevaluecreated_idx ON test ((lower(name) ||
lower(value)), created);

andreak=# EXPLAIN ANALYZE select * from test order by lower(name) ||
lower(value) ASC, created ASC;
QUERY PLAN
-----------------------------------------------------------------------------------------------------------------------------------------
Index Scan using test_lowernamevaluecreated_idx on test (cost=0.00..61.58
rows=770 width=72) (actual time=0.013..0.013 rows=0 loops=1)
Total runtime: 0.127 ms
(2 rows)

andreak=# EXPLAIN ANALYZE select * from test order by lower(name) ||
lower(value) ASC, created DESC;
QUERY PLAN
--------------------------------------------------------------------------------------------------------
Sort (cost=60.39..62.32 rows=770 width=72) (actual time=0.034..0.034 rows=0
loops=1)
Sort Key: (lower((name)::text) || lower((value)::text)), created
-> Seq Scan on test (cost=0.00..23.47 rows=770 width=72) (actual
time=0.004..0.004 rows=0 loops=1)
Total runtime: 0.123 ms
(4 rows)

As the EXPLAIN-output shows, the index is not used when sort-ordering differs
in the two order-by-columns.
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?

In my application I often have a need to sort by more than 3 columns, so I'm
really wondering if there is a way to make sorting of multiple columsn (each
which may have different sort-order) use an index? Preferrably without having
to create 2^N indexes.

--
Andreas Joseph Krogh <andreak(at)officenet(dot)no>
Senior Software Developer / Manager
------------------------+---------------------------------------------+
OfficeNet AS | The most difficult thing in the world is to |
Karenslyst Allé 11 | know how to do a thing and to watch |
PO. Box 529 Skøyen | somebody else doing it wrong, without |
0214 Oslo | comment. |
NORWAY | |
Tlf: +47 24 15 38 90 | |
Fax: +47 24 15 38 91 | |
Mobile: +47 909 56 963 | |
------------------------+---------------------------------------------+

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Gerardo Herzig 2007-08-10 15:11:08 Re: Install two different versions of postgres which should run in parallel
Previous Message Giuseppe Sacco 2007-08-10 12:44:10 Re: Install two different versions of postgres which should run in parallel