Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to have postgres ignore inserts with a duplicate key but keep going

I am inserting record data in a collection in memory into postgres and want the database to ignore any record that already exists in the database (by virtue of having the same primary key) but keep going with the rest of my inserts.

I'm using clojure and hugsql, btw, but I'm guessing the answer might be language agnostic.

As I'm essentially treating the database as a set in this way I may be engaging in an antipattern.

like image 609
THX1137 Avatar asked Nov 28 '17 21:11

THX1137


People also ask

How do I ignore duplicate entries?

Use the INSERT IGNORE command rather than the INSERT command. If a record doesn't duplicate an existing record, then MySQL inserts it as usual. If the record is a duplicate, then the IGNORE keyword tells MySQL to discard it silently without generating an error.

How do I ignore duplicate keys in SQL?

If you choose Ignore duplicate key, SQL Server will issue a warning message, ignore the offending incoming row and try to insert the remaining rows of the bulk insert operation. If you do not choose Ignore duplicate key, SQL Server will issue an error message and roll back the entire bulk insert operation.


1 Answers

If you're using Postgres 9.5 or newer (which I assume you are, since it was released back in January 2016), there's a very useful ON CONFLICT cluase you can use:

INSERT INTO mytable (id, col1, col2)
VALUES (123, 'some_value', 'some_other_value')
ON CONFLICT (id) DO NOTHING
like image 179
Mureinik Avatar answered Nov 15 '22 18:11

Mureinik