Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Performance & internals
Stage 5: Specialization

Part 11 / Topic 5 of 7

Upsert: ON CONFLICT

"Insert it — unless it exists, then update it." Without database support this is a race condition (check-then-insert fails under concurrency); with it, it's one atomic statement. Track stock counts:

CREATE TABLE inventory (
  product_id integer PRIMARY KEY,
  stock      integer NOT NULL
);
INSERT INTO inventory VALUES (1, 15), (2, 8);
INSERT INTO inventory (product_id, stock)
VALUES (1, 5), (3, 25)
ON CONFLICT (product_id)
DO UPDATE SET stock = inventory.stock + EXCLUDED.stock;
SELECT * FROM inventory ORDER BY product_id;
CREATE TABLE
INSERT 0 2
INSERT 0 2
 product_id | stock 
------------+-------
          1 |    20
          2 |     8
          3 |    25
(3 rows)

Read the pieces: the conflict target (product_id) names a unique constraint; EXCLUDED is the row you tried to insert; the table name (inventory.stock) is the row already there. Product 1: 15 + 5 = 20 (updated); product 3: fresh insert. DO NOTHING is the quieter variant — "insert unless present, either way don't error" — the standard idempotent-import tool.

🧪 Quick quiz — answer from memory, then check.

  1. In DO UPDATE SET stock = inventory.stock + EXCLUDED.stock, what are the two sides?
  2. Why can't check-then-insert replace ON CONFLICT?
Show the answers
  1. inventory.stock = the existing row; EXCLUDED.stock = the row the INSERT proposed.
  2. Between your check and your insert, another session can insert — ON CONFLICT is atomic, the check-then-insert pair is not.

Exercise 5: The visit counter

What to do: A page_visits (path PRIMARY KEY, visits) table where recording a visit is always the same one statement — first visit inserts 1, repeats increment. Record /home twice and /pricing once.

Sample output:

   path   | visits 
----------+--------
 /home    |      2
 /pricing |      1
(2 rows)

💡 Hint: ON CONFLICT (path) DO UPDATE SET visits = page_visits.visits + 1.


Show the solution to Exercise 5
-- Exercise 5: The visit counter (idempotent upsert)
DROP TABLE IF EXISTS page_visits;
CREATE TABLE page_visits (
  path   text PRIMARY KEY,
  visits integer NOT NULL
);
INSERT INTO page_visits VALUES ('/home', 1)
ON CONFLICT (path) DO UPDATE SET visits = page_visits.visits + 1;
INSERT INTO page_visits VALUES ('/home', 1)
ON CONFLICT (path) DO UPDATE SET visits = page_visits.visits + 1;
INSERT INTO page_visits VALUES ('/pricing', 1)
ON CONFLICT (path) DO UPDATE SET visits = page_visits.visits + 1;
SELECT * FROM page_visits ORDER BY path;

Search the guide