Sub topic 11
Inserting or updating with ON CONFLICT
This chapter assumes you know the books table from earlier chapters, including its UNIQUE constraint on isbn13, and that you are comfortable with INSERT ... RETURNING and basic constraints. You need PostgreSQL 9.5 or newer. The tutorial already requires version 12 or newer, so you have it.
The problem: loading the same book twice
Suppose you import a CSV of books every week. Some rows are new and some were loaded last week, perhaps with a corrected page count. A plain INSERT fails on the repeats:
INSERT INTO books (title, isbn13, page_count)
VALUES ('Example Title', '9780000000001', 320);
-- ERROR: duplicate key value violates unique constraint "books_isbn13_key"You could check first with a SELECT and then choose between INSERT and UPDATE. That has a race. Another session can insert the same ISBN between your check and your insert, and then one of you gets the error anyway.
INSERT ... ON CONFLICT moves the decision into a single statement. PostgreSQL tries the insert and, if the new row would violate the unique index you name, does something else instead. The check and the action are atomic, so concurrent sessions cannot interleave between them.
The two actions
ON CONFLICT has two actions.
DO NOTHINGsilently skips the row that conflicts.DO UPDATEchanges the existing row instead.
Here is the upsert from the plan:
INSERT INTO books (title, isbn13, page_count)
VALUES ('Example Title', '9780000000001', 340)
ON CONFLICT (isbn13) DO UPDATE
SET title = EXCLUDED.title,
page_count = EXCLUDED.page_count;The pieces:
(isbn13)is the conflict target. It names the unique index PostgreSQL uses to detect a duplicate. This index is called the arbiter.EXCLUDEDis a special table alias. It holds the row you tried to insert, soEXCLUDED.page_countis340.- The table name (
books) refers to the row already stored. InsideSETandWHERE,books.page_countis the old value.
If no book has that ISBN, the row is inserted. If one does, its title and page_count are overwritten. Running the statement again changes nothing further, which makes it idempotent: running it once or ten times leaves the same data.
Choosing the conflict target
The target must match a unique index or constraint exactly. For books, (isbn13) works because of the UNIQUE constraint. If nothing matches, PostgreSQL refuses to run the statement:
ERROR: there is no unique or exclusion constraint matching the ON CONFLICT specificationYou can also name the constraint instead of its columns:
INSERT INTO books (title, isbn13)
VALUES ('Example Title', '9780000000001')
ON CONFLICT ON CONSTRAINT books_isbn13_key DO NOTHING;Naming columns is usually better. It survives a constraint rename and reads more clearly.
For DO NOTHING, the target is optional. Without one, any unique violation is skipped. DO UPDATE requires a target, because PostgreSQL must know which row to update.
A conflict target covers only one index. If a row violates a different unique constraint, the statement still raises an error. In this schema books has only one unique constraint besides the primary key, and the identity primary key never conflicts, so this rarely matters here. Keep it in mind for tables with several unique columns.
NULL values never conflict
UNIQUE treats each NULL as distinct. A book inserted with isbn13 set to NULL cannot conflict with another such book, so an upsert keyed on isbn13 will insert a new row every time. If you import books without ISBNs, the upsert cannot deduplicate them. Either supply a different key or accept the duplicates.
Constraints still apply
The proposed row is checked against NOT NULL and CHECK constraints before the conflict logic runs. This statement fails even though the ISBN already exists:
INSERT INTO books (title, isbn13, page_count)
VALUES ('Example Title', '9780000000001', -5)
ON CONFLICT (isbn13) DO UPDATE SET page_count = EXCLUDED.page_count;
-- ERROR: new row for relation "books" violates check constraint "books_page_count_check"An upsert does not bypass validation. The updated row must also satisfy all constraints after the SET clause runs.
Updating only some columns
Columns you leave out of SET keep their stored values. Often you want to avoid replacing good data with a missing value. A batch row may have no published_year, which arrives as NULL. COALESCE keeps the old value in that case:
INSERT INTO books (title, isbn13, published_year, page_count)
VALUES ('Example Title', '9780000000001', NULL, 340)
ON CONFLICT (isbn13) DO UPDATE
SET title = EXCLUDED.title,
page_count = EXCLUDED.page_count,
published_year = COALESCE(EXCLUDED.published_year, books.published_year);Skipping no-op updates with WHERE
By default, DO UPDATE rewrites the existing row even when no value changes. PostgreSQL then creates a new row version, which adds table bloat and write-ahead log volume. In a weekly import where most rows are unchanged, that cost adds up. Add a WHERE clause to DO UPDATE so only genuinely different rows are written:
INSERT INTO books (title, isbn13, page_count)
VALUES
('Example Title', '9780000000001', 340),
('Another Example', '9780000000002', 280)
ON CONFLICT (isbn13) DO UPDATE
SET title = EXCLUDED.title,
page_count = EXCLUDED.page_count
WHERE (books.title, books.page_count)
IS DISTINCT FROM (EXCLUDED.title, EXCLUDED.page_count)
RETURNING book_id, title;IS DISTINCT FROM is used instead of <> because it treats NULL as a comparable value. With <>, a comparison involving NULL returns NULL, and the row would be skipped when it should be updated.
RETURNING and what it hides
RETURNING works with ON CONFLICT DO UPDATE and returns both inserted and updated rows. Rows skipped by DO NOTHING, or filtered out by the DO UPDATE ... WHERE clause, produce no output row. This surprises people who use DO NOTHING ... RETURNING book_id to fetch an id: for an existing book it returns nothing.
To get the id either way, look it up in a second step:
WITH ins AS (
INSERT INTO books (title, isbn13)
VALUES ('Another Example', '9780000000002')
ON CONFLICT (isbn13) DO NOTHING
RETURNING book_id
)
SELECT book_id FROM ins
UNION ALL
SELECT book_id FROM books WHERE isbn13 = '9780000000002'
LIMIT 1;If the insert happened, ins supplies the id. Otherwise the second query finds the existing row. When the insert did happen, the second query would also see no new row (it runs on the same snapshot), so LIMIT 1 returns the first branch's row.
Upserts on the join table
book_authors has a composite primary key on (book_id, author_id), so DO NOTHING makes linking idempotent:
INSERT INTO book_authors (book_id, author_id)
SELECT b.book_id, a.author_id
FROM books b
CROSS JOIN authors a
WHERE b.isbn13 = '9780000000001'
AND a.name = 'Example Author'
ON CONFLICT (book_id, author_id) DO NOTHING;You can run this repeatedly without creating a second link or an error. The authors table has no unique column besides its id, so you cannot upsert authors by name unless you add UNIQUE (name). Adding it is a modeling decision: two real people can share a name.
Gotchas
- Duplicates inside one statement. With
DO UPDATE, a singleINSERTthat contains the same ISBN twice fails withON CONFLICT DO UPDATE command cannot affect row a second time. PostgreSQL will not update one row twice in one command. Deduplicate the input first, for example withSELECT DISTINCT ON (isbn13).DO NOTHINGdoes not have this restriction. - Gaps in identity values. Identity sequence values are consumed before the conflict is detected. Every skipped or updated row burns a
book_id. Gaps are harmless, but do not treat the ids as a gapless count. - Triggers and cascades. Update triggers run for rows that take the
DO UPDATEpath, and insert triggers run for the attempted insert. Foreign key references to the row are unaffected as long as you don't change its key. - Changing the key itself. Setting
isbn13 = EXCLUDED.isbn13in the update is pointless, since they are equal. Setting a different unique column can raise a new unique violation.
Choosing between the actions
| Situation | Use |
|---|---|
| Insert if new, ignore if it exists | `DO NOTHING` |
| The latest input should win | `DO UPDATE SET ...` |
| Fill in only missing values | `DO UPDATE` with `COALESCE` |
| Most input rows are unchanged | `DO UPDATE ... WHERE ... IS DISTINCT FROM` |
Exercise
A weekly import runs INSERT INTO books (title, isbn13) VALUES ('Old Book', NULL) ON CONFLICT (isbn13) DO NOTHING;. After three runs, how many 'Old Book' rows exist, and why? How would you prevent the duplicates?
Show answer
Three rows exist. UNIQUE treats NULL values as distinct, so a NULL isbn13 never conflicts and the insert always succeeds. To prevent duplicates, give the book a real ISBN, choose another unique key such as a (title, published_year) constraint if that fits your data, or check for an existing row before inserting.
Exercise
Write an upsert for books keyed on isbn13 that updates pagecount only when the stored value differs from the new one, and that returns the bookid for every row actually inserted or changed.
Show answer
INSERT INTO books (title, isbn13, pagecount) VALUES ('Example Title', '9780000000001', 340) ON CONFLICT (isbn13) DO UPDATE SET pagecount = EXCLUDED.pagecount WHERE books.pagecount IS DISTINCT FROM EXCLUDED.pagecount RETURNING bookid;