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'd think a unique index including any extra columns would make this version of your INSERT work:
drop table if exists testtable;
create table testtable (pk int primary key, foo text, bar te
+xt);
create unique index foobar_idx on testtable (pk, foo, bar);
INSERT INTO testtable (pk, foo, bar) VALUES (1, 'Hello', 'World') ON C
+ONFLICT (pk,foo,bar) DO NOTHING;
INSERT INTO testtable (pk, foo, bar) VALUES (1, 'Hello', 'World') ON C
+ONFLICT (pk,foo,bar) DO NOTHING;
INSERT INTO testtable (pk, foo, bar) VALUES (1, 'Hello', 'Quz' ) ON C
+ONFLICT (pk,foo,bar) DO NOTHING;
which yields:
drop table if exists testtable;
DROP TABLE
create table testtable (pk int primary key, foo text, bar te
+xt);
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 C
+ONFLICT (pk,foo,bar) DO NOTHING;
INSERT 0 1
INSERT INTO testtable (pk, foo, bar) VALUES (1, 'Hello', 'World') ON C
+ONFLICT (pk,foo,bar) DO NOTHING;
INSERT 0 0
INSERT INTO testtable (pk, foo, bar) VALUES (1, 'Hello', 'Quz' ) ON C
+ONFLICT (pk,foo,bar) DO NOTHING;
ERROR: duplicate key value violates unique constraint "testtable_pkey
+"
DETAIL: Key (pk)=(1) already exists.
Postgres 12.1 (but this works from 9.5.x onward)
Manual PostgreSQL 12.1: INSERT # SQL-ON-CONFLICT
update: The first INSERT should be the same, of course, fixed. Also, removed vestiges of the original bash-version.
update 2: 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?
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.