Received: from maia.hub.org (unknown [200.46.204.183]) by mail.postgresql.org (Postfix) with ESMTP id 7A3256328F5 for ; Mon, 12 Apr 2010 07:06:57 -0300 (ADT) Received: from mail.postgresql.org ([200.46.204.86]) by maia.hub.org (mx1.hub.org [200.46.204.183]) (amavisd-maia, port 10024) with ESMTP id 33186-07 for ; Mon, 12 Apr 2010 10:06:46 +0000 (UTC) X-Greylist: from auto-whitelisted by SQLgrey-1.7.6 Received: from 27.mail-out.ovh.net (27.mail-out.ovh.net [91.121.30.210]) by mail.postgresql.org (Postfix) with SMTP id 99D69633EEF for ; Mon, 12 Apr 2010 07:06:46 -0300 (ADT) Received: (qmail 24256 invoked by uid 503); 12 Apr 2010 10:11:23 -0000 Received: from b9.ovh.net (HELO mail629.ha.ovh.net) (213.186.33.59) by 27.mail-out.ovh.net with SMTP; 12 Apr 2010 10:11:22 -0000 Received: from b0.ovh.net (HELO queueout) (213.186.33.50) by b0.ovh.net with SMTP; 12 Apr 2010 10:06:45 -0000 Received: from par69-8-88-161-102-87.fbx.proxad.net (HELO immo.peufeu.com) (lists%peufeu.com@88.161.102.87) by ns0.ovh.net with SMTP; 12 Apr 2010 10:06:45 -0000 Content-Type: text/plain; charset=utf-8; format=flowed; delsp=yes To: Corin , pgsql-performance@postgresql.org Subject: Re: planer chooses very bad plan References: <4BC23B3E.5020500@gmail.com> Date: Mon, 12 Apr 2010 12:06:41 +0200 MIME-Version: 1.0 Content-Transfer-Encoding: 8bit From: "Pierre C" Message-ID: In-Reply-To: <4BC23B3E.5020500@gmail.com> User-Agent: Opera Mail/10.10 (Linux) X-Ovh-Tracer-Id: 17344769540060284620 X-Ovh-Remote: 88.161.102.87 (par69-8-88-161-102-87.fbx.proxad.net) X-Ovh-Local: 213.186.33.20 (ns0.ovh.net) X-Spam-Check: DONE|U 0.5/N X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=0 tagged_above=-10 required=5 tests=none X-Spam-Level: X-Archive-Number: 201004/147 X-Sequence-Number: 38397 > explain analyze SELECT * FROM "telegrams" WHERE ((recipient_id=508933 > AND recipient_deleted=FALSE) OR (user_id=508933 AND user_deleted=FALSE)) > ORDER BY id DESC LIMIT 10 OFFSET 0 If you need very fast performance on this query, you need to be able to use the index for ordering. Note that the following query will only optimize the first page of results in the case you want to display BOTH sent and received telegrams. - Create an index on (recipient_id, id) WHERE NOT recipient_deleted - Create an index on (user_id, id) WHERE NOT user_deleted - Drop redundant indexes (recipient_id) and (user_id) SELECT * FROM ( SELECT * FROM "telegrams" WHERE recipient_id=508933 AND recipient_deleted=FALSE ORDER BY id DESC LIMIT 10 UNION ALL SELECT * FROM "telegrams" WHERE user_id=508933 AND user_deleted=FALSE ORDER BY id DESC LIMIT 10 ) AS foo ORDER BY id DESC LIMIT 10; These indexes will also optimize the queries where you only display the inbox and outbox, in which case it will be able to use the index for ordering on any page, because there will be no UNION.