Received: from maia.hub.org (maia-5.hub.org [200.46.204.29]) by mail.postgresql.org (Postfix) with ESMTP id E2BDFB5DC13 for ; Wed, 21 Sep 2011 12:02:50 -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 25795-09 for ; Wed, 21 Sep 2011 15:02:44 +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 8581CB5DC01 for ; Wed, 21 Sep 2011 12:02:44 -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 p8LF2hs6023040; Wed, 21 Sep 2011 11:02:43 -0400 (EDT) To: Thomas Kappler cc: pgsql-performance@postgresql.org Subject: Re: Slow query with self-join, group by, 100m rows In-reply-to: References: Comments: In-reply-to Thomas Kappler message dated "Tue, 20 Sep 2011 19:43:27 +0200" Date: Wed, 21 Sep 2011 11:02:42 -0400 Message-ID: <23039.1316617362@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: 201109/328 X-Sequence-Number: 45104 Thomas Kappler writes: > The query we want to do is (with example values): > select t.cid, count(distinct t1.subject_id) > from termindex t1, termindex t2 > where t1.cid=20642 and t1.indextype=636 and t2.indextype=636 and > t2.subject_id=t1.subject_id > group by t2.cid; The EXPLAIN output you provided doesn't appear to match this query (in particular, I don't see the indextype restrictions being checked anyplace in the plan). One quick-and-dirty thing that might help is to raise work_mem enough so that (1) you get a hash aggregation not a sort/group one, and (2) if there are still any sorts being done, they don't spill to disk. That will probably be a higher number than would be prudent to install as a global setting, but you could SET it locally in the current session before issuing the expensive query. regards, tom lane