Received: from maia.hub.org (maia-5.hub.org [200.46.204.29]) by mail.postgresql.org (Postfix) with ESMTP id ABDCEB5DC07 for ; Thu, 27 Oct 2011 21:26:51 -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 51039-05 for ; Fri, 28 Oct 2011 00:26:45 +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 86C22B5DBF0 for ; Thu, 27 Oct 2011 21:26:45 -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 p9S0QiGn009301; Thu, 27 Oct 2011 20:26:44 -0400 (EDT) To: Ty Busby cc: pgsql-sql@postgresql.org Subject: Re: optimize self-join query In-reply-to: References: Comments: In-reply-to Ty Busby message dated "Tue, 25 Oct 2011 14:37:02 -0400" Date: Thu, 27 Oct 2011 20:26:44 -0400 Message-ID: <9300.1319761604@sss.pgh.pa.us> From: Tom Lane X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=-2.404 tagged_above=-5 required=5 tests=BAYES_00=-1.9, RP_MATCHES_RCVD=-0.504 X-Spam-Level: X-Archive-Number: 201110/82 X-Sequence-Number: 35966 Ty Busby writes: > I have a table that stores a very large starting number called epc_start_numeric and a quantity. I've apparently built the most inefficient query possible for doing the job I need: find out if any records overlap. Imagine the epc_start_numeric + quantity representing a block of numbers. I need to find out if any of these blocks overlap. Yeah, overlap is a hard problem. Basically, Postgres doesn't have any way to do your query short of comparing each row to each other row, so the cost goes up as O(N^2). If you know more than you've let on about the properties of the intervals, you might be able to improve things. For instance if the intervals fall into nonoverlapping buckets then you could add a constraint that the buckets of the two sides are equal. Postgres is a lot better with equality join constraints than it is with range constraints, so it would be able to match up rows and only do the O(N^2) work within each bucket. In the long run we might have better answers --- Jeff Davis has been working on range types for years now, and one of the long-range goals of that is to have smarter support for this type of problem. But for now, it's going to be painful. regards, tom lane