Received: from maia.hub.org (maia-5.hub.org [200.46.204.29]) by mail.postgresql.org (Postfix) with ESMTP id 69ABE63296A for ; Fri, 10 Sep 2010 23:00:48 -0300 (ADT) Received: from mail.postgresql.org ([200.46.204.86]) by maia.hub.org (mx1.hub.org [200.46.204.29]) (amavisd-maia, port 10024) with ESMTP id 74678-08 for ; Sat, 11 Sep 2010 02:00:41 +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 012BC6327FB for ; Fri, 10 Sep 2010 23:00:40 -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 o8B20cNe005324; Fri, 10 Sep 2010 22:00:38 -0400 (EDT) To: Mason Harding cc: pgsql-performance@postgresql.org Subject: Re: Slow SQL lookup due to every field being listed in SORT KEY In-reply-to: References: Comments: In-reply-to Mason Harding message dated "Fri, 10 Sep 2010 15:35:17 -0700" Date: Fri, 10 Sep 2010 22:00:38 -0400 Message-ID: <5323.1284170438@sss.pgh.pa.us> From: Tom Lane X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=-1.91 tagged_above=-10 required=5 tests=BAYES_00=-1.9, T_RP_MATCHES_RCVD=-0.01 X-Spam-Level: X-Archive-Number: 201009/49 X-Sequence-Number: 40252 Mason Harding writes: > Hi all. I Have the following query (tested in postgres 8.4 and 9.0rc1) > SELECT distinct event0_.* > FROM event event0_ inner join account account1_ on > event0_.account_id_owner=account1_.account_id > LEFT OUTER JOIN friend friendcoll2_ ON > account1_.account_id=friendcoll2_.friend_account_id > WHERE (event0_.account_id_owner=2 or friendcoll2_.account_id=2 > AND friendcoll2_.status=2 AND (event0_.is_recomended is null OR > event0_.is_recomended=false)) > ORDER BY event0_.event_id DESC LIMIT 25 > None of the tables listed here have more than a couple of thousand rows, and > are all indexed. If I run that query as is, it will take up to 5 seconds, > if I remove the ORDER BY and LIMIT, it will run into about 200 ms. The reason it's sorting by all the columns is the DISTINCT: that's implemented by a sort-and-unique type of scheme so it has to be sure that all the columns are sorted. You didn't show the non-ORDER-BY plan, but I suspect it's preferring a hash aggregation approach to doing the DISTINCT if it doesn't have to produce sorted output. The easiest way to make that query faster would be to raise work_mem enough so that the sort doesn't have to spill to disk. regards, tom lane