Received: from maia.hub.org (maia-3.hub.org [200.46.204.243]) by mail.postgresql.org (Postfix) with ESMTP id B9393B5DC2C for ; Fri, 28 Oct 2011 06:32:17 -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 75276-04 for ; Fri, 28 Oct 2011 09:32:11 +0000 (UTC) X-Greylist: from auto-whitelisted by SQLgrey-1.8.0-rc2 Received: from lo.gmane.org (lo.gmane.org [80.91.229.12]) by mail.postgresql.org (Postfix) with ESMTP id 93CCCB5DC26 for ; Fri, 28 Oct 2011 06:32:11 -0300 (ADT) Received: from list by lo.gmane.org with local (Exim 4.69) (envelope-from ) id 1RJinK-0004DQ-Az for pgsql-sql@postgresql.org; Fri, 28 Oct 2011 11:32:10 +0200 Received: from 212.126.222.122 ([212.126.222.122]) by main.gmane.org with esmtp (Gmexim 0.1 (Debian)) id 1AlnuQ-0007hv-00 for ; Fri, 28 Oct 2011 11:32:10 +0200 Received: from hari.fuchs by 212.126.222.122 with local (Gmexim 0.1 (Debian)) id 1AlnuQ-0007hv-00 for ; Fri, 28 Oct 2011 11:32:10 +0200 X-Injected-Via-Gmane: http://gmane.org/ To: pgsql-sql@postgresql.org From: Harald Fuchs Subject: Re: optimize self-join query Date: Fri, 28 Oct 2011 11:31:58 +0200 Lines: 37 Message-ID: <86sjmdlawh.fsf@protecting.net> References: Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii X-Complaints-To: usenet@dough.gmane.org X-Gmane-NNTP-Posting-Host: 212.126.222.122 X-Archive: encrypt User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/23.1 (gnu/linux) Cancel-Lock: sha1:675Mk4YIht8utLaqJ8iPely2HDA= X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=-1.229 tagged_above=-5 required=5 tests=BAYES_00=-1.9, FREEMAIL_FROM=0.001, RCVD_NUMERIC_HELO=1.164, RP_MATCHES_RCVD=-0.504, T_TO_NO_BRKTS_FREEMAIL=0.01 X-Spam-Level: X-Archive-Number: 201110/86 X-Sequence-Number: 35970 In article , 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. If I understand you correctly, you want to compare numeric intervals. On PgFoundry you can find an interval type like that called bioseg. This type is GiST-indexable and thus may speed up your query. Example: CREATE TABLE test2 ( id serial NOT NULL, seg bioseg NOT NULL, PRIMARY KEY (id) ); -- Fill test2 with a gazillion of rows CREATE INDEX test2_seg_ix ON test2 USING gist (seg); SELECT t1.id, t1.seg, t2.id, t2.seg FROM test2 t1 JOIN test2 t2 ON t2.id != t1.id AND t2.seg && t1.seg; You'll still need a seqscan for t1, but t2 will use an index scan. You can even define a table constraint to prevent overlaps: ALTER TABLE test2 ADD CONSTRAINT test2_seg_ex EXCLUDE USING gist (seg WITH &&);