From: | Ken Williams <ken(at)mathforum(dot)org> |
---|---|
To: | pgsql-general(at)postgresql(dot)org |
Subject: | Problem with indexes, LIMIT, ORDER BY ... DESC |
Date: | 2002-06-07 08:32:09 |
Message-ID: | 0EAAF6F6-79F1-11D6-9D1C-0003936C1626@mathforum.org |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | pgsql-general |
Hi,
I'm having trouble with indexes in PostgreSQL 7.1.3. Here is a
transcript:
==========================================================================
=
announce=# \d foo
Table "foo"
Attribute | Type | Modifier
-----------+--------------------------+----------
code | character varying(4) | not null
date | timestamp with time zone | not null
price | numeric(10,2) | not null
volume | integer | not null
other | boolean | not null
Index: foo_code_date
announce=# \d foo_code_date
Index "foo_code_date"
Attribute | Type
-----------+--------------------------
code | character varying(4)
date | timestamp with time zone
btree
announce=# explain select date from foo where date < '06/08/2001
23:59' and code = 'FOO' order by code, date limit 1;
NOTICE: QUERY PLAN:
Limit (cost=0.00..3.78 rows=1 width=20)
-> Index Scan using foo_code_date on foo
(cost=0.00..23996.55 rows=6355 width=20)
==========================================================================
=
So far, so good. The index is properly used, and the query is
fast. However, if I want to sort *descending* (which is really
what I want to do, to find the closest row with a date less than
a given date), then a full table scan is done:
==========================================================================
=
announce=# explain select date from foo where date < '06/08/2001
23:59' and code = 'FOO' order by code, date DESC limit 1;
NOTICE: QUERY PLAN:
Limit (cost=24397.98..24397.98 rows=1 width=20)
-> Sort (cost=24397.98..24397.98 rows=6355 width=20)
-> Index Scan using foo_code_date on foo
(cost=0.00..23996.55 rows=6355 width=20)
==========================================================================
=
What can I do to improve this?
Might it help if I reversed the order of the fields in the
index? There are only about 50 possible values for the 'code'
field. I'm not sure which order is better in this case. The
'date' field is well spread out over a year.
-Ken
From | Date | Subject | |
---|---|---|---|
Next Message | Bertin, Philippe | 2002-06-07 09:34:10 | Are globally defined constants possible at all ? |
Previous Message | Arthur | 2002-06-07 06:52:42 | Slow connection |