Received: from maia.hub.org (maia-3.hub.org [200.46.204.243]) by mail.postgresql.org (Postfix) with ESMTP id 78AD7B5DBD9 for ; Fri, 14 Oct 2011 01:26:02 -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 65876-02 for ; Fri, 14 Oct 2011 04:25:55 +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 9FA0FB5DBD8 for ; Fri, 14 Oct 2011 01:25:55 -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 p9E4PrVE013280; Fri, 14 Oct 2011 00:25:53 -0400 (EDT) To: James Cranch cc: pgsql-performance@postgresql.org Subject: Re: Rapidly finding maximal rows In-reply-to: References: Comments: In-reply-to James Cranch message dated "10 Oct 2011 22:59:17 +0100" Date: Fri, 14 Oct 2011 00:25:53 -0400 Message-ID: <13279.1318566353@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/135 X-Sequence-Number: 45357 James Cranch writes: > I have a slow query. I expect that there is either a more intelligent way > to write it, or that one could make some indexes that would speed it up. > I've tried various indexes, and am not getting anywhere. > I'd be grateful for any suggestions. Reasonably full details are below. Two bits of advice: 1. Avoid unnecessary use of WITH. It acts as an optimization fence, which you don't want here. In particular, the only way to avoid sorting/aggregating over the whole table is for the outer query's WHERE conditions on competition_name and academic_year_beginning to get pushed down into the scans on challenge_entries ... and that can't happen if there's a WITH in between. 2. Try increasing work_mem. I think that your first view would work all right if it had enough work_mem to go for a HashAgg plan instead of sort-and-group, even without pushdown of the outer WHERE. It'd definitely be faster than what you've got, anyway. The other approach with a window function is probably a lost cause. Postgres hasn't got a lot of intelligence about optimizing window-function queries ... regards, tom lane