AI Hints
Home›PostgreSQL Tutorial›Upsert, Generated Columns, ALTER
PostgreSQL · Lesson 22 of 120

Upsert with ON CONFLICT

Insert or update.

⏱ 2 min read▶ Video at 18:20🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

Every night, a supplier sends stock counts. Some books are new, and some already exist. Upsert inserts new rows, and updates the ones that are already there.

  • Nightly stock file
  • New or existing?
  • Upsert

Insert or update stock

On conflict watches the book ID. If it already exists, do update sets the new stock. Excluded means the row we tried to insert. Run it. Book one is updated, and book thirty one is new.

query.sqlsql
INSERT INTO books (book_id, title, author, genre, price, stock)
VALUES (1,  'The Silent Orchard', 'Mira Hale', 'Mystery', 14.99, 75),
       (31, 'River Songs', 'Ana Silva', 'Romance', 11.99, 20)
ON CONFLICT (book_id)
DO UPDATE SET stock = excluded.stock
RETURNING book_id, title, stock;
Output
 book_id |       title        | stock
---------+--------------------+-------
       1 | The Silent Orchard |    75
      31 | River Songs        |    20
(2 rows)

INSERT 0 2

Upsert options

On conflict needs a unique column or constraint to watch. Do nothing skips duplicates quietly. Do update can use a where clause too. And returning shows what happened.

keyvalue
ON CONFLICT (col)needs unique
DO NOTHINGskip
DO UPDATE SETmerge
excluded.colthe new value

Summary

Insert on conflict either updates the existing row, or does nothing. Next, columns that calculate themselves.

Key takeaways
  • ON CONFLICT
  • DO UPDATE
  • excluded
Next up: Generated Columns — computed and stored