Received: from localhost (unknown [200.46.208.211]) by mail.postgresql.org (Postfix) with ESMTP id 98E476345B9 for ; Thu, 26 Mar 2009 12:50:34 -0300 (ADT) Received: from mail.postgresql.org ([200.46.204.86]) by localhost (mx1.hub.org [200.46.208.211]) (amavisd-maia, port 10024) with ESMTP id 62509-03 for ; Thu, 26 Mar 2009 12:50:26 -0300 (ADT) X-Greylist: from auto-whitelisted by SQLgrey-1.7.6 Received: from sss.pgh.pa.us (sss.pgh.pa.us [66.207.139.130]) by mail.postgresql.org (Postfix) with ESMTP id B5E026339A9 for ; Thu, 26 Mar 2009 12:49:57 -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 n2QFngu6022530; Thu, 26 Mar 2009 11:49:42 -0400 (EDT) To: Matthew Wakeling cc: pgsql-performance@postgresql.org Subject: Re: Very specialised query In-reply-to: References: Comments: In-reply-to Matthew Wakeling message dated "Thu, 26 Mar 2009 14:30:55 -0000" Date: Thu, 26 Mar 2009 11:49:42 -0400 Message-ID: <22529.1238082582@sss.pgh.pa.us> From: Tom Lane X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=0.013 tagged_above=0 required=5 tests=AWL=0.013 X-Spam-Level: X-Archive-Number: 200903/384 X-Sequence-Number: 33306 Matthew Wakeling writes: > This query takes about two hours. > Now, it happens that there is an algorithm for calculating overlaps which > is really quick. It involves iterating through the table in order of the > start variable and keeping a list of ranges which "haven't ended yet". > When you read the next range from the table, you firstly purge all the > ranges from the list that end before the beginning of the new range. Then, > you output a result row for each element in the list combined with the new > range, then you add the new range to the list. > This algorithm just doesn't seem to fit into SQL at all. No, it doesn't. Have you thought about coding it in plpgsql? I have a feeling that it might be possible to do it using SQL:2003 recursive queries, but the procedural coding is likely to be easier to understand and better-performing. Not to mention that you won't have to wait for 8.4... regards, tom lane