X-Original-To: pgsql-admin-postgresql.org@localhost.postgresql.org Received: from localhost (unknown [200.46.204.2]) by svr1.postgresql.org (Postfix) with ESMTP id 95430D1E91C for ; Tue, 23 Mar 2004 17:56:46 +0000 (GMT) Received: from svr1.postgresql.org ([200.46.204.71]) by localhost (neptune.hub.org [200.46.204.2]) (amavisd-new, port 10024) with ESMTP id 95611-06 for ; Tue, 23 Mar 2004 13:56:44 -0400 (AST) Received: from wolff.to (wolff.to [66.93.249.74]) by svr1.postgresql.org (Postfix) with SMTP id 1CD2FD1E414 for ; Tue, 23 Mar 2004 13:56:43 -0400 (AST) Received: (qmail 26819 invoked by uid 500); 23 Mar 2004 17:59:43 -0000 Date: Tue, 23 Mar 2004 11:59:43 -0600 From: Bruno Wolff III To: Rob Anderson Cc: pgsql-admin@postgresql.org Subject: Re: Testing for existence of a record before insert Message-ID: <20040323175943.GA26654@wolff.to> Mail-Followup-To: Rob Anderson , pgsql-admin@postgresql.org References: Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline In-Reply-To: User-Agent: Mutt/1.5.6i X-Virus-Scanned: by amavisd-new at postgresql.org X-Archive-Number: 200403/301 X-Sequence-Number: 12870 On Tue, Mar 23, 2004 at 16:41:40 -0000, Rob Anderson wrote: > I am trying to find a way of performing something similar to the SQL-Server SQL of > > IF NOT EXISTS (SELECT id FROM a_table WHERE id='akey') > THEN INSERT INTO a_table (id, name) values ('akey', 'adetails'); INSERT INTO a_table (id, name) SELECT 'akey' as id, 'adetails' as name where not exists (SELECT id FROM a_table WHERE id='akey') It is still possible for two transactions to both try to insert the same value at the same time. You either need to be prepared to handle the occasional error or you need to get an exclusive lock on a_table.