Re: Query with Max, Order by is very slow.......

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Sam Barnett-Cormack <s(dot)barnett-cormack(at)lancaster(dot)ac(dot)uk>
Cc: Hemapriya <priyam_1121(at)yahoo(dot)com>, pgsql-admin(at)postgresql(dot)org
Subject: Re: Query with Max, Order by is very slow.......
Date: 2004-04-08 02:07:01
Message-ID: 7199.1081390021@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-admin

Sam Barnett-Cormack <s(dot)barnett-cormack(at)lancaster(dot)ac(dot)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

In response to

Browse pgsql-admin by date

  From Date Subject
Next Message Grega Bremec 2004-04-08 04:33:04 Re: [PERFORM] Raw devices vs. Filesystems
Previous Message Bruno Wolff III 2004-04-08 01:57:32 Re: Query with Max, Order by is very slow.......