Re: how do i avoid multiple sessions from inserting the

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Kolus Maximiliano <Kolus(dot)maximiliano(at)bcr(dot)com(dot)ar>
Cc: patrick(dot)fiche(at)aqsacom(dot)com, pgsql-general(at)postgresql(dot)org
Subject: Re: how do i avoid multiple sessions from inserting the
Date: 2003-02-24 20:56:25
Message-ID: 5449.1046120185@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Kolus Maximiliano <Kolus(dot)maximiliano(at)bcr(dot)com(dot)ar> writes:
> I tried, but it's giving me an error, as if INSERT wouldn't like the WHERE:
> INSERT INTO users (email) VALUES ('john(at)doe(dot)com')
> WHERE NOT EXISTS
> (SELECT id FROM users WHERE email='john(at)doe(dot)com');
> ERROR: parser: parse error at or near "WHERE"

This is not correct syntax: INSERT...VALUES doesn't take WHERE.
But INSERT...SELECT does:

INSERT INTO users (email)
SELECT 'john(at)doe(dot)com'
WHERE NOT EXISTS
(SELECT id FROM users WHERE email='john(at)doe(dot)com');

However, as a method of avoiding duplicate-key errors this is useless :-(

In my opinion the easiest approach is to just go ahead and roll back
the transaction when you get a dup-key error, and try again from the
top. So:

try UPDATE; if succeed then done
else try INSERT; if succeed then done
else ROLLBACK, start again

In practice rollbacks are going to be pretty infrequent, so this is
not inefficient --- certainly no worse than any other solution.

regards, tom lane

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Ed L. 2003-02-24 20:59:02 Re: PostgreSQL Replication Server licensing
Previous Message Ericson Smith 2003-02-24 20:53:14 Re: 7.4?