Sub topic 2
Starting point: a plain INSERT and its duplicate-key error
An upsert exists to solve one specific failure: a plain INSERT that collides with a row already in the table. This chapter reproduces that failure and shows exactly what PostgreSQL reports. It then looks at what the failure does to your statement and transaction, and why the two usual hand-written workarounds are not enough. The ON CONFLICT syntax itself comes in later chapters.
What this chapter assumes
You should already be comfortable with these:
- Basic SQL:
SELECT,INSERT,UPDATE. - Primary keys and unique constraints, at the level of "the database rejects a second row with the same key".
- Running statements in
psqlor another PostgreSQL client.
Everything here runs on any supported PostgreSQL version.
The table used throughout
The tutorial uses a small stock table. Each product is identified by a SKU (stock keeping unit), a text code that must be unique.
DROP TABLE IF EXISTS product_stock;
CREATE TABLE product_stock (
sku text PRIMARY KEY,
quantity integer NOT NULL,
updated_at timestamptz NOT NULL DEFAULT now()
);The PRIMARY KEY on sku does two jobs. It declares that sku is NOT NULL, and it creates a unique index named product_stock_pkey. That index is what PostgreSQL consults on every insert to decide whether a row with the same SKU already exists.
You did not name the index. PostgreSQL derived the name from the table and the kind of constraint. Remember the name, because it appears in the error message and can be used later to identify a conflict.
The first insert works, the second does not
Insert one row:
INSERT INTO product_stock (sku, quantity) VALUES ('A-100', 5);INSERT 0 1The command tag INSERT 0 1 means one row was inserted. The leading 0 is a legacy object identifier field that is always zero in modern versions. Now run the identical statement again:
INSERT INTO product_stock (sku, quantity) VALUES ('A-100', 5);ERROR: duplicate key value violates unique constraint "product_stock_pkey"
DETAIL: Key (sku)=(A-100) already exists.The table is unchanged. It still holds exactly one row for A-100, with the quantity from the first insert.
Reading the error
The error carries more than the headline. Each piece is useful when you write error handling or debug a pipeline.
| Part | Example | What it tells you |
|---|---|---|
| Severity and message | `ERROR: duplicate key value violates unique constraint "product_stock_pkey"` | A unique rule was broken, and which one. |
| Constraint name | `product_stock_pkey` | The unique index that rejected the row. Client libraries expose it as a field. |
| Detail | `Key (sku)=(A-100) already exists.` | The column list and the offending values. |
| SQLSTATE | `23505` | A five-character code for the error class. This is `unique_violation`. |
Application code should match on the SQLSTATE 23505, not on the message text. The text can change with the server's language setting, while the code is stable. In PL/pgSQL (PostgreSQL's procedural language) the same condition is called unique_violation.
SQLSTATE 23505 is specific to unique indexes and unique constraints, including primary keys. A foreign-key failure is 23503, a NOT NULL failure is 23502, and a CHECK failure is 23514. Handling the whole 23xxx class as "duplicate" is a common bug.
Unique constraint versus unique index
A UNIQUE or PRIMARY KEY constraint is implemented by a unique index, so both produce the same error. A plain CREATE UNIQUE INDEX with no constraint also raises 23505. The message then says "violates unique constraint" in both cases, and the name shown is the index's name. This equivalence matters in the later chapters on conflict targets.
What the error does to the statement
A failed INSERT is all or nothing. If a multi-row statement contains one duplicate, no row from that statement is stored.
INSERT INTO product_stock (sku, quantity)
VALUES ('C-300', 1), ('A-100', 9);ERROR: duplicate key value violates unique constraint "product_stock_pkey"
DETAIL: Key (sku)=(A-100) already exists.Check what landed:
SELECT sku, quantity FROM product_stock ORDER BY sku; sku | quantity
-------+----------
A-100 | 5
(1 row)C-300 is missing even though it was valid and listed first. The statement is the unit of failure. This matters for bulk loads. One bad row fails the whole batch, and the error names only the first conflict it hit, not all of them.
What the error does to the transaction
Inside an explicit transaction the consequences are larger. After any error, PostgreSQL marks the whole transaction as aborted. Every later command is refused until you roll back.
BEGIN;
INSERT INTO product_stock (sku, quantity) VALUES ('A-100', 5);
SELECT count(*) FROM product_stock;
ROLLBACK;ERROR: duplicate key value violates unique constraint "product_stock_pkey"
DETAIL: Key (sku)=(A-100) already exists.
ERROR: current transaction is aborted, commands ignored until end of transaction block
ROLLBACKThe SELECT was perfectly valid. It was rejected because the transaction was already poisoned by the earlier failure. Any work done earlier in the same transaction is also lost when you roll back.
A savepoint lets you recover without discarding the whole transaction:
BEGIN;
SAVEPOINT before_insert;
INSERT INTO product_stock (sku, quantity) VALUES ('A-100', 5);
ROLLBACK TO SAVEPOINT before_insert;
SELECT count(*) FROM product_stock;
COMMIT;After ROLLBACK TO SAVEPOINT, the transaction is usable again and the SELECT runs. The first INSERT still prints the duplicate-key error, as before.
Savepoints work, but each one starts a subtransaction. Wrapping every row of a large load in its own savepoint has a real cost, and it is clumsy to write. Many client libraries do this silently when you ask them to "ignore duplicates", so be aware of it.
Two workarounds that look reasonable
Before ON CONFLICT, people handled this problem in application code. Both approaches are still common, and both have problems that the upsert syntax was designed to remove.
Workaround 1: check first, then insert
The idea is to look for the row, then decide.
SELECT 1 FROM product_stock WHERE sku = 'A-100';
-- application: if no row came back, run:
INSERT INTO product_stock (sku, quantity) VALUES ('A-100', 5);
-- otherwise, run an UPDATE insteadThis is two statements, and another session can act between them. Suppose two sessions run this for the same new SKU at the same time:
The check was correct when it ran and stale by the time of the insert. Wrapping both statements in a transaction does not fix this at the default READ COMMITTED isolation level. Neither session's SELECT sees the other's uncommitted insert, so both pass. The unique index is the only thing that reliably stops the second row. The check-first pattern therefore still needs error handling, so it adds a round trip without removing the error.
Workaround 2: insert and catch the error
The second approach accepts the error and handles it. Here it is in PL/pgSQL, with the fallback being an update:
DO $$
BEGIN
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 7);
EXCEPTION WHEN unique_violation THEN
UPDATE product_stock
SET quantity = 7, updated_at = now()
WHERE sku = 'A-100';
END
$$;This avoids the race on the insert, because the unique index is the arbiter. It has three weaknesses:
- A block with an
EXCEPTIONclause starts a subtransaction on every execution, the same cost as the savepoint approach above. - The
UPDATEcan find no row if another session deleted it after the failed insert. The robust version needs a retry loop, which is more code to get wrong. - It cannot handle a batch. One duplicate aborts the multi-row insert, and the handler does not know which row was the culprit.
What both workarounds are missing
Both approaches try to build "insert, or else update" from separate pieces. The correct behavior needs three guarantees together:
- The decision of whether the row exists is made by the unique index, not by an earlier read.
- The insert and the fallback action happen as one atomic step.
- A conflict is a normal outcome, not an error that aborts the transaction.
INSERT ... ON CONFLICT provides all three in one statement. The next chapters build it up piece by piece, starting with how the conflict is detected.
A side effect worth knowing early
A failed insert can still consume values from a sequence. If a table has an identity or serial column, PostgreSQL draws the next value before it checks the unique index. The failed row leaves a gap in the numbering. Sequences are never rolled back, so the gap is permanent. product_stock uses a text key, so you cannot see this here. The later chapter on pitfalls shows it with the app_user table.
Summary of the failure modes
| Situation | What happens |
|---|---|
| Single-row insert of an existing key | Error `23505`, no row stored. |
| Multi-row insert with one duplicate | Error `23505`, none of the rows stored. |
| Error inside a transaction block | Transaction aborted until `ROLLBACK` or `ROLLBACK TO SAVEPOINT`. |
| Check with `SELECT`, then `INSERT` | Race: concurrent sessions can still hit `23505`. |
| Catch the exception and `UPDATE` | Correct for one row, but costly and needs a retry loop to be fully safe. |
Exercises
Exercise
A table has a primary key on sku. You run INSERT INTO product_stock (sku, quantity) VALUES ('X-1', 1), ('A-100', 2), ('X-2', 3); and A-100 already exists. Which of the three rows are in the table afterwards, and which SQLSTATE does the client receive?
Show answer
None of the three rows are stored. A single statement succeeds or fails as a whole, so the valid rows X-1 and X-2 are rolled back along with the duplicate. The client receives SQLSTATE 23505 (unique_violation).
Exercise
Inside BEGIN ... COMMIT, an INSERT fails with a duplicate-key error and your next statement is a harmless SELECT. What happens to the SELECT, and what are two ways to continue working?
Show answer
The SELECT is rejected with "current transaction is aborted, commands ignored until end of transaction block", because any error aborts the whole transaction. You can issue ROLLBACK and start over, or set a SAVEPOINT before the insert and run ROLLBACK TO SAVEPOINT after the failure so the transaction becomes usable again.
Exercise
Why does running SELECT to check for a row and then INSERT only if none is found not remove the duplicate-key error under concurrency?
Show answer
Another session can insert the same key between your SELECT and your INSERT. At READ COMMITTED, your SELECT cannot see that session's uncommitted row, so it finds nothing, and your INSERT then hits the unique index and fails with 23505. The check and the insert are separate steps, so the gap between them cannot be closed by application logic alone.