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

From Tom Lane
Subject Re: Query with Max, Order by is very slow.......
Date
Msg-id 7199.1081390021@sss.pgh.pa.us
Whole thread Raw
In response to Re: Query with Max, Order by is very slow.......  (Sam Barnett-Cormack <s.barnett-cormack@lancaster.ac.uk>)
List pgsql-admin
Sam Barnett-Cormack <s.barnett-cormack@lancaster.ac.uk> writes:
> On Wed, 7 Apr 2004, Hemapriya wrote:
>> Column   |            Type             | Modifiers
>> -----------+-----------------------------+-----------
>> origindb  | character(1)                | not null
>> uid       | integer                     | not null
>> ...
>> Indexes:
>> "request_pkey" primary key, btree (origindb, uid)
>>
>> select max(uid) from request where originDB=1;

> You really want an index on origindb and uid -

He's got one ;-).

The real problem with this is the datatype mismatch is preventing use of
the index.  The query should be

    select max(uid) from request where originDB='1';

or else change the datatype of origindb to be integer.

This query will still want to access all the rows with originDB='1',
however.  If there are a lot of those then you'll want to use the
order by/limit hack.  Correct application of the hack to this case
goes like

regression=# explain select uid from request where originDB='1' order by originDB desc, uid desc limit 1;
                                         QUERY PLAN
--------------------------------------------------------------------------------------------
 Limit  (cost=0.00..3.41 rows=1 width=9)
   ->  Index Scan Backward using request_pkey on request  (cost=0.00..17.07 rows=5 width=9)
         Index Cond: (origindb = '1'::bpchar)
(3 rows)

If EXPLAIN doesn't show you a sort-free plan then you haven't gotten it
right.

            regards, tom lane

pgsql-admin by date:

Previous
From: Bruno Wolff III
Date:
Subject: Re: Query with Max, Order by is very slow.......
Next
From: Grega Bremec
Date:
Subject: Re: [PERFORM] Raw devices vs. Filesystems