Sub topic 2
Starting Point: A Plain INSERT and Its Duplicate-Key Error
This chapter assumes that you know basic SELECT, INSERT, and UPDATE statements. You should also know that a primary key identifies a row and that a unique constraint prevents duplicate values. The examples use PostgreSQL and can be run in psql or another PostgreSQL client.
An upsert combines an insert with a response to a duplicate key. Before writing an upsert, it helps to see what a normal INSERT does when a key already exists.
Create a table with a unique key
Suppose an inventory table stores one row for each stock-keeping unit, or SKU. The sku column is the primary key, so PostgreSQL must reject two rows with the same SKU.
CREATE TABLE product_stock (
sku text PRIMARY KEY,
quantity integer NOT NULL,
updated_at timestamptz NOT NULL DEFAULT now()
);A primary key creates a uniqueness rule. PostgreSQL also creates an index that helps it find conflicting values efficiently. The NOT NULL constraints require every row to have a quantity, while updated_at gets the current time when a row is inserted.
Insert the first row:
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 5);This statement succeeds because no row currently has the key A-100.
What happens on a duplicate
Run the same insert again:
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 5);PostgreSQL rejects it with an error similar to this:
ERROR: duplicate key value violates unique constraint "product_stock_pkey"
DETAIL: Key (sku)=(A-100) already exists.The second statement does not update the existing row. It does not silently skip the new value. The complete statement fails.
The error identifies the unique constraint that detected the conflict and the key value that caused it. PostgreSQL reports a duplicate-key error with SQLSTATE 23505, which applications can catch, but handling the error in application code is often less useful than expressing the intended behavior directly in SQL.
Why the duplicate matters
The two rows may have the same sku but different data:
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 8);PostgreSQL still cannot decide what 8 means. It might mean:
- Replace the current quantity with
8. - Add
8to the current quantity. - Ignore the new value.
- Reject the operation because changing stock requires another process.
A plain INSERT chooses rejection. An upsert lets you choose another action with ON CONFLICT.
The database performs the uniqueness check, rather than relying on a separate query. This distinction becomes important when multiple clients write at the same time.
The unsafe check-then-insert pattern
A common application pattern is:
SELECT 1
FROM product_stock
WHERE sku = 'A-100';If no row is returned, the application then runs:
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 5);This creates a race condition. A race condition is a result that depends on the timing of concurrent operations. Two clients can both run the SELECT before either client runs the INSERT. Both conclude that the SKU is available. One insert succeeds, and the other receives the duplicate-key error.
A unique constraint still protects the data, but the application must now handle the error. An upsert places the conflict action in one database statement, allowing PostgreSQL to coordinate the uniqueness check and the requested action.
The next step is to identify the key that PostgreSQL should use as the conflict target. For this table, that key is sku, because sku is backed by the primary key constraint.
Exercise
Why does the second INSERT for sku = 'A-100' fail instead of changing the existing row?
Show answer
A plain INSERT only requests a new row. The primary key requires every sku to be unique, so PostgreSQL raises a duplicate-key error when that value already exists.