Skip to content
Advertisement

Avoid primary key constraint violation in postgres

I have an application where insertion is a part of a transaction. Now the value to be inserted comes from the user, so it may violate the primary key constraint of uniqueness. But I do not wish to abort the full transaction if an exception is raised, I want to ignore and move on to complete the rest of the inserts in the transaction. I am new to Postgres, I was wondering if triggers can be the way to implement this feature. If not triggers then what? Any help is appreciated.

Advertisement

Answer

you can use on conflict in your upsert operations :

insert into table ([list of columns])
values ([list of values])
on conflict (id) DO NOTHING ;

I assumed id is your primary key

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement