Skip site navigation (1) Skip section navigation (2)

Re: Check before insert

From: Michael Fuhr <mike(at)fuhr(dot)org>
To: Robert Perry <rlperry(at)lodestonetechnologies(dot)com>
Cc: pgsql-interfaces(at)postgresql(dot)org
Subject: Re: Check before insert
Date: 2005-03-15 22:23:29
Message-ID: (view raw, whole thread or download thread mbox)
Lists: pgsql-interfaces
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

In response to

pgsql-interfaces by date

Next:From: Christof PetigDate: 2005-03-16 14:12:56
Subject: libecpg (8.0 and CVS) hits a gcc bug on powerpc and amd64 (crash)
Previous:From: Robert PerryDate: 2005-03-15 21:51:20
Subject: Re: Check before insert

Privacy Policy | About PostgreSQL
Copyright © 1996-2017 The PostgreSQL Global Development Group