X-Original-To: pgsql-interfaces-postgresql.org@localhost.postgresql.org Received: from localhost (unknown [200.46.204.144]) by svr1.postgresql.org (Postfix) with ESMTP id 21561564BE for ; Tue, 15 Mar 2005 22:23:52 +0000 (GMT) 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 44484-04 for ; Tue, 15 Mar 2005 22:23:42 +0000 (GMT) Received: from tigger.fuhr.org (tigger.fuhr.org [63.214.45.158]) by svr1.postgresql.org (Postfix) with ESMTP id 2F5BC54EBA for ; Tue, 15 Mar 2005 22:23:41 +0000 (GMT) Received: from winnie.fuhr.org (winnie.fuhr.org [10.1.0.1]) by tigger.fuhr.org (8.13.3/8.13.3) with ESMTP id j2FMNU8g021239 (version=TLSv1/SSLv3 cipher=DHE-RSA-AES256-SHA bits=256 verify=OK); Tue, 15 Mar 2005 15:23:32 -0700 (MST) (envelope-from mfuhr@winnie.fuhr.org) Received: from winnie.fuhr.org (localhost [127.0.0.1]) by winnie.fuhr.org (8.13.3/8.13.3) with ESMTP id j2FMNTBc067827; Tue, 15 Mar 2005 15:23:29 -0700 (MST) (envelope-from mfuhr@winnie.fuhr.org) Received: (from mfuhr@localhost) by winnie.fuhr.org (8.13.3/8.13.3/Submit) id j2FMNTo1067826; Tue, 15 Mar 2005 15:23:29 -0700 (MST) (envelope-from mfuhr) Date: Tue, 15 Mar 2005 15:23:29 -0700 From: Michael Fuhr To: Robert Perry Cc: pgsql-interfaces@postgresql.org Subject: Re: Check before insert Message-ID: <20050315222329.GA67743@winnie.fuhr.org> References: <1110920863.42374e9f75aa1@sms.ed.ac.uk> <55762d9369dc9fd5b85b8662ccdf8557@lodestonetechnologies.com> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline In-Reply-To: <55762d9369dc9fd5b85b8662ccdf8557@lodestonetechnologies.com> X-Virus-Scanned: by amavisd-new at hub.org X-Spam-Status: No, hits=0.004 tagged_above=0 required=5 tests=AWL X-Spam-Level: X-Archive-Number: 200503/47 X-Sequence-Number: 5376 On Tue, Mar 15, 2005 at 04:51:20PM -0500, Robert Perry wrote: > Insert (protein_id, name) > select 'P04667', 'Albumin' > where > not exists(select * from protein_table_name where protein_id = > 'P04667') This should work if concurrency isn't an issue. But if two concurrent transactions execute the same statement, then they might both find no existing row and thus both attempt the insert. In that case, in the presence of a unique index, one of the inserts will succeed and the other transaction will block pending the first transaction's completion. If the first transaction rolls back then the second's insert will succeed, but if the first transaction commits then the second will fail with a duplicate key violation. A program should therefore be prepared to handle this situation. In 8.0 and later you could use a savepoint or a PL/pgSQL exception handler to recover from the error without aborting the entire transaction. -- Michael Fuhr http://www.fuhr.org/~mfuhr/