Received: from localhost (unknown [200.46.208.211]) by mail.postgresql.org (Postfix) with ESMTP id 27056633958 for ; Sat, 9 Jan 2010 13:07:27 -0400 (AST) Received: from mail.postgresql.org ([200.46.204.86]) by localhost (mx1.hub.org [200.46.208.211]) (amavisd-maia, port 10024) with ESMTP id 19686-08 for ; Sat, 9 Jan 2010 17:07:15 +0000 (UTC) X-Greylist: from auto-whitelisted by SQLgrey-1.7.6 Received: from sss.pgh.pa.us (sss.pgh.pa.us [66.207.139.130]) by mail.postgresql.org (Postfix) with ESMTP id 7DC4A63385E for ; Sat, 9 Jan 2010 13:07:16 -0400 (AST) Received: from sss2.sss.pgh.pa.us (tgl@localhost [127.0.0.1]) by sss.pgh.pa.us (8.14.2/8.14.2) with ESMTP id o09H7C3r008144; Sat, 9 Jan 2010 12:07:12 -0500 (EST) To: Richard Neill cc: pgsql-performance@postgresql.org Subject: Re: Joint index including MAX() ? In-reply-to: <4B487A8F.6000003@cam.ac.uk> References: <4B487A8F.6000003@cam.ac.uk> Comments: In-reply-to Richard Neill message dated "Sat, 09 Jan 2010 12:46:07 +0000" Date: Sat, 09 Jan 2010 12:07:12 -0500 Message-ID: <8143.1263056832@sss.pgh.pa.us> From: Tom Lane X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=-2.456 tagged_above=-10 required=5 tests=AWL=0.143, BAYES_00=-2.599 X-Spam-Level: X-Archive-Number: 201001/169 X-Sequence-Number: 37049 Richard Neill 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