Upsert with ON CONFLICT
- Version
- 19
- Since
- 9.5
- Review
- Draft
Summary#
ON CONFLICT chooses what happens when a proposed row violates a unique index or exclusion constraint. DO UPDATE changes the existing row, DO NOTHING skips the proposal and DO SELECT returns the existing row. Exclusion constraints work only with DO NOTHING.
Syntax#
INSERT INTO table_name AS t (column_list)
VALUES (value_list)
ON CONFLICT (key_column) DO UPDATE
SET value_column = EXCLUDED.value_column
WHERE condition
RETURNING old.value_column, new.value_column;
INSERT INTO table_name (column_list)
VALUES (value_list)
ON CONFLICT (key_column) DO NOTHING
RETURNING column_list;
INSERT INTO table_name (column_list)
VALUES (value_list)
ON CONFLICT (key_column) DO SELECT [FOR UPDATE]
RETURNING column_list;
Example#
The output below is from PostgreSQL 19.0, produced with psql -X -q -A -P null=NULL -v ON_ERROR_STOP=1 -f example.sql in a scratch database. The script rolls back at the end, so it leaves nothing behind.
BEGIN;
CREATE TEMPORARY TABLE stock (
sku text PRIMARY KEY,
quantity integer NOT NULL
);
INSERT INTO stock VALUES ('bolt', 10), ('nut', 4);
-- Add to an existing row or create a new one.
WITH changed AS (
INSERT INTO stock AS s (sku, quantity)
VALUES ('bolt', 5), ('screw', 7)
ON CONFLICT (sku) DO UPDATE
SET quantity = s.quantity + EXCLUDED.quantity
RETURNING sku, old.quantity AS before, new.quantity AS after
)
SELECT sku, before, after FROM changed ORDER BY sku;
-- DO NOTHING returns only the rows that were inserted.
INSERT INTO stock (sku, quantity)
VALUES ('nut', 100)
ON CONFLICT (sku) DO NOTHING
RETURNING sku, quantity;
-- DO SELECT returns the existing row and leaves it unchanged.
INSERT INTO stock (sku, quantity)
VALUES ('nut', 100)
ON CONFLICT (sku) DO SELECT
RETURNING sku, quantity;
SELECT sku, quantity FROM stock ORDER BY sku;
ROLLBACK;
Expected output#
sku|before|after
bolt|10|15
screw|NULL|7
(2 rows)
sku|quantity
(0 rows)
sku|quantity
nut|4
(1 row)
sku|quantity
bolt|15
nut|4
screw|7
(3 rows)
Common mistakes#
ERROR: duplicate key value violates unique constraint comes from a write that repeats a key. To handle it in an INSERT, add ON CONFLICT with the columns or constraint that raised it.
One DO UPDATE statement cannot affect the same row twice, so deduplicate the proposed conflict keys. DO NOTHING ... RETURNING yields rows only for inserts. A DO UPDATE ... WHERE condition that is false can still leave the conflicting row locked, with no row in RETURNING.
Version applicability#
PostgreSQL 9.5 added ON CONFLICT with DO NOTHING and DO UPDATE. The old and new names in RETURNING require PostgreSQL 18. DO SELECT is new in PostgreSQL 19; it requires a conflict target and a RETURNING clause.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0