Re: how do i avoid multiple sessions from inserting the - Mailing list pgsql-general

From Dmitry Tkach
Subject Re: how do i avoid multiple sessions from inserting the
Date
Msg-id 3E5A8B45.7070407@openratings.com
Whole thread Raw
In response to Re: how do i avoid multiple sessions from inserting the  (Kolus Maximiliano <Kolus.maximiliano@bcr.com.ar>)
List pgsql-general
>
> INSERT INTO users (email) VALUES ('john@doe.com')
>     WHERE NOT EXISTS
>         (SELECT id FROM users WHERE email='john@doe.com');
>
> ERROR:  parser: parse error at or near "WHERE"
>
> (Btw, i didnt know that INSERT would accept a WHERE clause)
>

Exactly. It will not.

You might do something like

insert into users (email)
select 'john@doe.com' where not exists (select 1 from users where email = 'john@doe.com');

This should work (syntactically), but, as I mentioned earlier, I doubt it will solve your problem, because it is still
possiblethat somebody 
else is inserting the same row right this moment, in which case your subquery will not see it until the other quy
commitsanyway, and you will have 
the same problem as before...

You have to either lock the table before checking if the row exists, or be able to handle the error you get after
insert
(in which case, you do not really need to check if it exists first - go straight to insert, and, if it fails, ignore
theerror) 

Dima



pgsql-general by date:

Previous
From: "scott.marlowe"
Date:
Subject: Re: A few questions to real pgsql gurus
Next
From: Kolus Maximiliano
Date:
Subject: Re: how do i avoid multiple sessions from inserting the