note
erix
<p><blockquote><i>
if the primary key exists, it should silently ignore the record if all the other columns match, but throw an error if they don't.
</i></blockquote></p>
<p>I'd think a unique index including any extra columns would make this version of your INSERT work:
<c>
drop table if exists testtable;
create table testtable (pk int primary key, foo text, bar text);
create unique index foobar_idx on testtable (pk, foo, bar);
INSERT INTO testtable (pk, foo, bar) VALUES (1, 'Hello', 'World') ON CONFLICT (pk,foo,bar) DO NOTHING;
INSERT INTO testtable (pk, foo, bar) VALUES (1, 'Hello', 'World') ON CONFLICT (pk,foo,bar) DO NOTHING;
INSERT INTO testtable (pk, foo, bar) VALUES (1, 'Hello', 'Quz' ) ON CONFLICT (pk,foo,bar) DO NOTHING;
</c>
<p>which yields:
<c>
drop table if exists testtable;
DROP TABLE
create table testtable (pk int primary key, foo text, bar text);
CREATE TABLE
create unique index foobar_idx on testtable (pk, foo, bar);
CREATE INDEX
INSERT INTO testtable (pk, foo, bar) VALUES (1, 'Hello', 'World') ON CONFLICT (pk,foo,bar) DO NOTHING;
INSERT 0 1
INSERT INTO testtable (pk, foo, bar) VALUES (1, 'Hello', 'World') ON CONFLICT (pk,foo,bar) DO NOTHING;
INSERT 0 0
INSERT INTO testtable (pk, foo, bar) VALUES (1, 'Hello', 'Quz' ) ON CONFLICT (pk,foo,bar) DO NOTHING;
ERROR: duplicate key value violates unique constraint "testtable_pkey"
DETAIL: Key (pk)=(1) already exists.
</c>
<p>Postgres 12.1 (but this works from 9.5.x onward)
<p>[ https://www.postgresql.org/docs/current/sql-insert.html#SQL-ON-CONFLICT | Manual PostgreSQL 12.1: INSERT # SQL-ON-CONFLICT ]
<p><b>update: </b>The first INSERT should be the same, of course, fixed. Also, removed vestiges of the original bash-version.
<p><b>update 2: </b> Re 'MySQL vs. Postgres': I think open-sourced and completely-free PostgreSQL is a better/safer choice than proprietary Oracle MySQL. For one thing, over time Pg will get better -- even better than Oracle -- but how could Oracle ever allow cheapo MySQL to overtake its venerable and expensive Oracle database product?
11107746
11107746