From: Tom Lane <tgl@sss.pgh.pa.us>
To: Sam Barnett-Cormack <s.barnett-cormack@lancaster.ac.uk>
Cc: Hemapriya <priyam_1121@yahoo.com>
Cc: pgsql-admin@postgresql.org
Subject: Re: Query with Max, Order by is very slow.......
Date: Wed, 07 Apr 2004 22:07:01 -0400
Message-ID: <7199.1081390021@sss.pgh.pa.us> (raw)
In-Reply-To: <Pine.LNX.4.58.0404072321340.3239@localhost.localdomain>
References: <20040407210354.79531.qmail@web21322.mail.yahoo.com>
<Pine.LNX.4.58.0404072321340.3239@localhost.localdomain>
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
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients from your mail client; the link fills in
the headers below: reply via email
Some clients, webmail especially, drop In-Reply-To and References from
a link, and the reply then starts a new thread: use the mbox below.
To: pgsql-admin@postgresql.org
Cc: tgl@sss.pgh.pa.us, s.barnett-cormack@lancaster.ac.uk, priyam_1121@yahoo.com
Subject: Re: Query with Max, Order by is very slow.......
In-Reply-To: <7199.1081390021@sss.pgh.pa.us>
References: <20040407210354.79531.qmail@web21322.mail.yahoo.com> <Pine.LNX.4.58.0404072321340.3239@localhost.localdomain> <7199.1081390021@sss.pgh.pa.us>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox