Received: from maia.hub.org (maia-3.hub.org [200.46.204.243]) by mail.postgresql.org (Postfix) with ESMTP id D0121B5DBD0 for ; Mon, 3 Oct 2011 12:12:39 -0300 (ADT) Received: from mail.postgresql.org ([200.46.204.86]) by maia.hub.org (mx1.hub.org [200.46.204.243]) (amavisd-maia, port 10024) with ESMTP id 08922-09 for ; Mon, 3 Oct 2011 15:12:33 +0000 (UTC) X-Greylist: from auto-whitelisted by SQLgrey-1.8.0-rc2 Received: from sss.pgh.pa.us (sss.pgh.pa.us [66.207.139.130]) by mail.postgresql.org (Postfix) with ESMTP id E9116B5DBF7 for ; Mon, 3 Oct 2011 12:12:32 -0300 (ADT) 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 p93FCV8f015616; Mon, 3 Oct 2011 11:12:31 -0400 (EDT) To: =?iso-8859-2?Q?Nowak_Micha=B3?= cc: pgsql-performance@postgresql.org Subject: Re: Query with order by and limit is very slow - wrong index used In-reply-to: <6B8FADC8-9692-439F-8AA4-0CAA287FCEB0@me.com> References: <6B8FADC8-9692-439F-8AA4-0CAA287FCEB0@me.com> Comments: In-reply-to =?iso-8859-2?Q?Nowak_Micha=B3?= message dated "Mon, 03 Oct 2011 11:44:21 +0200" Date: Mon, 03 Oct 2011 11:12:31 -0400 Message-ID: <15615.1317654751@sss.pgh.pa.us> From: Tom Lane X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=-2.404 tagged_above=-10 required=5 tests=BAYES_00=-1.9, RP_MATCHES_RCVD=-0.504 X-Spam-Level: X-Archive-Number: 201110/26 X-Sequence-Number: 45248 =?iso-8859-2?Q?Nowak_Micha=B3?= writes: > When I perform query such as this: "select * from records where source_id = 'XXX' order by id limit 200;" I expect DB to use index source_id_id_idx with XXX as filter. It is true for all but one values of XXX - when I ask for records with most common source_id, records_pkey index is used instead and performance is terrible! Explain analyze results below. I'm thinking it probably sees the pkey index as cheaper because that's highly correlated with the physical order of the table. (It would be useful to see pg_stats.correlation for these columns.) With a sufficiently unselective filter, scanning in pkey order looks cheaper than scanning in source_id order. If so, what you probably need to do to get the estimates more in line with reality is to reduce random_page_cost. That will reduce the assumed penalty for non-physical-order scanning. regards, tom lane