Re: Query with Max, Order by is very slow....... - Mailing list pgsql-admin

From Bruno Wolff III
Subject Re: Query with Max, Order by is very slow.......
Date
Msg-id 20040408015732.GA20746@wolff.to
Whole thread Raw
In response to Query with Max, Order by is very slow.......  (Hemapriya <priyam_1121@yahoo.com>)
List pgsql-admin
On Wed, Apr 07, 2004 at 14:03:54 -0700,
  Hemapriya <priyam_1121@yahoo.com> wrote:
> Indexes:
>     "request_pkey" primary key, btree (origindb, uid)
>
> I do max Query like this
>
> select max(uid) from request where originDB=1;
>
> it took around 20 min to return the result..  Since
> max, count functions do the full table scan, i tried
> the workaround given..
>
> select uid from request where originDB=1 order by uid
> desc limit 1;
>
> this query runs forever.. i tried even without where
> condition..no result..

Because the index is on both origindb and uid and the planner doesn't
know that it can use this index when origindb is fixed but you are
ordering on uid, you need to rewrite the query slightly.
Try using:
select uid from request where originDB=1
  order by origindb desc, uid desc limit 1;

pgsql-admin by date:

Previous
From: "Jaime Casanova"
Date:
Subject: Re: [admin] index in pk
Next
From: Tom Lane
Date:
Subject: Re: Query with Max, Order by is very slow.......