Re: Joint index including MAX() ?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Richard Neill <rn214@xxxxxxxxx> 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

-- 
Sent via pgsql-performance mailing list (pgsql-performance@xxxxxxxxxxxxxx)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-performance

[Postgresql General]     [Postgresql PHP]     [PHP Users]     [PHP Home]     [PHP on Windows]     [Kernel Newbies]     [PHP Classes]     [PHP Books]     [PHP Databases]     [Yosemite]

  Powered by Linux