From: | Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us> |
---|---|
To: | Richard Neill <rn214(at)cam(dot)ac(dot)uk> |
Cc: | pgsql-performance(at)postgresql(dot)org |
Subject: | Re: Joint index including MAX() ? |
Date: | 2010-01-09 17:07:12 |
Message-ID: | 8143.1263056832@sss.pgh.pa.us |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | pgsql-performance |
Richard Neill <rn214(at)cam(dot)ac(dot)uk> writes:
> I'm trying to optimise the speed of some selects with the where condition:
> WHERE id =
> (SELECT MAX(id) FROM tbl_sort_report WHERE parcel_id_code='43024')
> This is relatively slow, taking about 15-20ms, even though I have a
> joint index on both fields:
> CREATE INDEX testidx3 ON tbl_sort_report (id, parcel_id_code);
You've got the index column order backwards: to make this query fast,
it has to be on (parcel_id_code, id). The reason should be apparent
if you think about the index ordering. With the correct index, the
backend can descend the btree looking for the last entry with
parcel_id_code='43024', and when it hits it, that's the max id.
The other way round, the best available strategy using the index
is to search backwards from the end (highest id) hoping to hit a
row with parcel_id_code='43024'. That could take a long time.
Frequently the planner will think it's so slow that it shouldn't
even bother with the index, just seqscan.
regards, tom lane
From | Date | Subject | |
---|---|---|---|
Next Message | Nickolay | 2010-01-09 18:50:07 | Re: PG optimization question |
Previous Message | Dmitri Girski | 2010-01-09 16:36:50 | Re: pg_connect takes 3.0 seconds |