Sub topic 1
Why upserts need a unique constraint
Prerequisites
You should know basic SQL (SELECT, INSERT, UPDATE), understand primary keys and unique constraints, and be able to run statements in psql or another PostgreSQL client.
An upsert inserts a row, or updates the existing row when one with the same key already exists. PostgreSQL does this in one statement with INSERT ... ON CONFLICT. The database needs a unique constraint or unique index to decide that two rows share a key. Without one, ON CONFLICT has nothing to check, and the statement fails.
Starting point: a plain INSERT and its duplicate-key error
Create a table with a primary key, then insert a row:
CREATE TABLE product_stock (
sku text PRIMARY KEY,
quantity integer NOT NULL,
updated_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO product_stock (sku, quantity) VALUES ('A-100', 5);Run the same INSERT a second time. PostgreSQL rejects it with a unique violation on product_stock_pkey. The error protects the key, but it stops the write. An upsert avoids that stop.
Choosing a conflict target
The conflict target is the list of columns whose uniqueness PostgreSQL checks. It must match a unique index or unique constraint. Here, sku is the primary key, so ON CONFLICT (sku) works. If no unique index matches the column list, PostgreSQL raises an error.
Skipping duplicates with DO NOTHING
DO NOTHING tells PostgreSQL to skip the row when the key already exists. No error appears:
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 5)
ON CONFLICT (sku) DO NOTHING;If A-100 already exists, this statement inserts zero rows and reports INSERT 0 0. If the key is new, it inserts one row. The existing row keeps its old quantity, so use DO NOTHING when the first value should win.
Exercise
The productstock table already holds sku 'A-100' with quantity 5. What does `INSERT INTO productstock (sku, quantity) VALUES ('A-100', 9) ON CONFLICT (sku) DO NOTHING;` return, and what is the quantity afterward?
Show answer
It returns INSERT 0 0 with no error. The quantity stays 5 because DO NOTHING skips the proposed row.