X-Original-To: pgsql-performance-postgresql.org@localhost.postgresql.org Received: from localhost (av.hub.org [200.46.204.144]) by postgresql.org (Postfix) with ESMTP id E68B39DC951 for ; Mon, 20 Feb 2006 00:06:19 -0400 (AST) Received: from postgresql.org ([200.46.204.71]) by localhost (av.hub.org [200.46.204.144]) (amavisd-new, port 10024) with ESMTP id 84466-03 for ; Mon, 20 Feb 2006 00:06:17 -0400 (AST) X-Greylist: from auto-whitelisted by SQLgrey- Received: from pillette.com (adsl-67-119-5-202.dsl.snfc21.pacbell.net [67.119.5.202]) by postgresql.org (Postfix) with ESMTP id D86C99DC84A for ; Mon, 20 Feb 2006 00:06:16 -0400 (AST) Received: (from andrew@localhost) by pillette.com (8.11.6/8.11.6) id k1K46CB09448; Sun, 19 Feb 2006 20:06:12 -0800 Date: Sun, 19 Feb 2006 20:06:12 -0800 From: andrew@pillette.com Message-Id: <200602200406.k1K46CB09448@pillette.com> Subject: How to optimize a JOIN with BETWEEN? To: pgsql-performance@postgresql.org Cc: X-Originating-IP: 63.201.37.104 X-Mailer: Webmin 0.940 MIME-Version: 1.0 X-Virus-Scanned: by amavisd-new at hub.org X-Spam-Status: No, score=0.486 required=5 tests=[AWL=-0.064, NO_REAL_NAME=0.55] X-Spam-Score: 0.486 X-Spam-Level: Content-Type: text/plain Content-Transfer-Encoding: 7bit X-Archive-Number: 200602/315 X-Sequence-Number: 17301 Here's a simplified version of the schema: Table A has an ID field, an observation date, and other stuff. There are about 20K IDs and 3K observations per ID. Table B has a matching ID field, minimum and maximum dates, a code, and other stuff, about 0-50 records per ID. For a given ID, the dates in B never overlap. On A, the PK is (id, obsdate). On B, the PK is (id, mindate). I want SELECT a.id, b.code, AVG(other stuff) FROM A LEFT JOIN B ON a.id=b.id AND a.obsdate BETWEEN b.mindate AND b.maxdate GROUP BY 1,2; Is there a way to smarten the query to take advantage of the fact at most one record of B matches A? Also, I have a choice between using a LEFT JOIN or inserting dummy records into B to fill in the gaps in the covered dates, which would make exactly one matching record. Would this make a difference? Thanks.