X-Original-To: pgsql-performance-postgresql.org@localhost.postgresql.org Received: from localhost (unknown [200.46.204.144]) by svr1.postgresql.org (Postfix) with ESMTP id E35F15298E for ; Tue, 28 Jun 2005 14:42:15 -0300 (ADT) Received: from svr1.postgresql.org ([200.46.204.71]) by localhost (av.hub.org [200.46.204.144]) (amavisd-new, port 10024) with ESMTP id 06117-03 for ; Tue, 28 Jun 2005 17:42:06 +0000 (GMT) Received: from colo.samason.me.uk (unknown [69.55.228.22]) by svr1.postgresql.org (Postfix) with ESMTP id 804755298D for ; Tue, 28 Jun 2005 14:42:05 -0300 (ADT) Received: from colo.samason.me.uk (colo [69.55.228.22]) by colo.samason.me.uk (8.12.11/8.12.11) with ESMTP id j5SHg6Tb065062 for ; Tue, 28 Jun 2005 18:42:06 +0100 (BST) (envelope-from sam@colo.samason.me.uk) Received: (from sam@localhost) by colo.samason.me.uk (8.12.11/8.12.11/Submit) id j5SHg61x065061 for pgsql-performance@postgresql.org; Tue, 28 Jun 2005 18:42:06 +0100 (BST) (envelope-from sam) Date: Tue, 28 Jun 2005 18:42:05 +0100 From: Sam Mason To: pgsql-performance@postgresql.org Subject: Re: tricky query Message-ID: <20050628174205.GT62747@colo.samason.me.uk> Mail-Followup-To: Sam Mason , pgsql-performance@postgresql.org References: <6EE64EF3AB31D5448D0007DD34EEB3415C2BEC@Herge.rcsinc.local> <42C167C6.5070108@arbash-meinel.com> <42C16FE4.2020803@arbash-meinel.com> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline In-Reply-To: <42C16FE4.2020803@arbash-meinel.com> User-Agent: Mutt/1.4.2.1i X-Virus-Scanned: by amavisd-new at hub.org X-Spam-Status: No, hits=0 tagged_above=0 required=5 tests= X-Spam-Level: X-Archive-Number: 200506/570 X-Sequence-Number: 13207 John A Meinel wrote: >SELECT t1.id+1 as id_new FROM id_test t1 > WHERE NOT EXISTS > (SELECT t2.id FROM id_test t2 WHERE t2.id = t1.id+1) > ORDER BY t1.id LIMIT 1; This works well on sparse data, as it only requires as many index access as it takes to find the first gap. The simpler "NOT IN" version that everybody seems to have posted the first time round has a reasonably constant (based on the number of rows, not gap position) startup time but the actual time spent searching for the gap is much lower. I guess the version you use depends on how sparse you expect the data to be. If you expect your query to have to search through more than half the table before finding the gap then you're better off using the "NOT IN" version, otherwise the "NOT EXISTS" version is faster -- on my system anyway. Hope that's interesting! Sam