Re: Index problem - Mailing list pgsql-general

From Bruno Wolff III
Subject Re: Index problem
Date
Msg-id 20050613205608.GC1346@wolff.to
Whole thread Raw
In response to Index problem  (David Mitchell <david.mitchell@telogis.com>)
List pgsql-general
On Tue, Jun 14, 2005 at 08:37:38 +1200,
  David Mitchell <david.mitchell@telogis.com> wrote:
> I'm totally baffled as to why postgres won't use this index. I have a
> table "point" with an index on it as so:
>
> CREATE INDEX unit_point
>   ON point
>   USING btree
>   (unit_id, time);
>
> When I try the following query, it insists on using a seqscan:
>
> SELECT time FROM point
> WHERE unit_id = 95501 and flags & 64 = 64
> ORDER BY time DESC LIMIT 1;

This is spooky. There has been a rash of questions all with the same issue
over the last several days. It must be a sign that an improvement should
get added to 8.1 before feature freeze.

Anyway, you need to rewrite the query to help out the planner:
SELECT time FROM point
WHERE unit_id = 95501 and flags & 64 = 64
ORDER BY unit_id DESC, time DESC LIMIT 1;

Currently the planner can't tell that the unit_id being constant allows
it to use the index when ordering by time. Adding it explicitly to the
order by clause is equivalent but will allow the planner to see that it can
use the index. Note that you need to match directions as well.

pgsql-general by date:

Previous
From: Bruno Wolff III
Date:
Subject: Re: PG 8.0.1 is getting slow in 24 hours. Only daily VACUUM FULL helps
Next
From: Eric E
Date:
Subject: Re: return next and pl/perl