Sub topic 3
Choosing a conflict target
The conflict target is the part of ON CONFLICT that names which uniqueness rule counts as a conflict. This chapter assumes you can write a basic INSERT, know what primary keys and unique constraints are, and can run statements in psql or another PostgreSQL client. It also assumes you have seen ON CONFLICT DO NOTHING and DO UPDATE at a basic level. Later chapters cover them in detail.
What the conflict target does
A conflict target appears right after ON CONFLICT. It tells PostgreSQL which unique index to check for a duplicate. Every index that the target selects is called an arbiter index.
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 5)
ON CONFLICT (sku) DO UPDATE
SET quantity = EXCLUDED.quantity;Here (sku) is the conflict target. PostgreSQL looks for a unique index or constraint on sku, uses it as the arbiter, and runs the DO UPDATE action only when the arbiter finds an existing row.
There are three ways to write a target:
- A column list, optionally with an index predicate:
ON CONFLICT (sku). - An expression, for expression indexes:
ON CONFLICT (lower(email)). - A constraint name:
ON CONFLICT ON CONSTRAINT product_stock_pkey.
The first two use inference. PostgreSQL works out which unique index you mean from the columns and predicate you wrote. The third names the constraint directly.
Inference by column list
With a column list, PostgreSQL searches for a unique index whose columns are exactly the columns you listed. Two details matter:
- Order does not matter.
(sku, warehouse_id)and(warehouse_id, sku)select the same index. - The set must match exactly. A subset or a superset of the index columns does not match.
CREATE TABLE warehouse_stock (
warehouse_id integer NOT NULL,
sku text NOT NULL,
quantity integer NOT NULL,
PRIMARY KEY (warehouse_id, sku)
);
-- Works: both key columns, in any order.
INSERT INTO warehouse_stock (warehouse_id, sku, quantity)
VALUES (1, 'A-100', 5)
ON CONFLICT (sku, warehouse_id) DO UPDATE
SET quantity = EXCLUDED.quantity;
-- Fails: sku alone is not covered by any unique index.
INSERT INTO warehouse_stock (warehouse_id, sku, quantity)
VALUES (1, 'A-100', 5)
ON CONFLICT (sku) DO UPDATE
SET quantity = EXCLUDED.quantity;
-- ERROR: there is no unique or exclusion constraint matching
-- the ON CONFLICT specificationThat error is the most common conflict-target mistake. It means inference found no matching unique index. Check three things:
- The index is unique. A plain index is not enough.
- The listed columns are exactly the index columns.
- For a partial or expression index, the predicate or expression matches (covered below).
When a table has several unique indexes
Tables often have more than one unique rule. The conflict target selects which rules are handled by the upsert. Any other unique rule still raises an error.
CREATE TABLE account (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL UNIQUE,
handle text NOT NULL UNIQUE,
display_name text NOT NULL
);
INSERT INTO account (email, handle, display_name)
VALUES ('[email protected]', 'ada', 'Ada');
-- Same email: handled by the upsert, display_name is updated.
INSERT INTO account (email, handle, display_name)
VALUES ('[email protected]', 'ada', 'Ada L.')
ON CONFLICT (email) DO UPDATE
SET display_name = EXCLUDED.display_name;
-- Different email, same handle: not handled by the target.
INSERT INTO account (email, handle, display_name)
VALUES ('[email protected]', 'ada', 'Grace')
ON CONFLICT (email) DO UPDATE
SET display_name = EXCLUDED.display_name;
-- ERROR: duplicate key value violates unique constraint "account_handle_key"The third statement fails because the arbiter is only the email index. The handle index still enforces uniqueness the normal way. Often this is what you want: an unexpected duplicate handle is a real data problem, and the error exposes it. If you wanted to hide such problems, you would have to design for that on purpose. A single ON CONFLICT clause with DO UPDATE cannot handle two different unique rules at once.
Naming a constraint with ON CONSTRAINT
Instead of listing columns, you can name a constraint:
INSERT INTO account (email, handle, display_name)
VALUES ('[email protected]', 'ada', 'Ada L.')
ON CONFLICT ON CONSTRAINT account_email_key DO UPDATE
SET display_name = EXCLUDED.display_name;PostgreSQL generated account_email_key for the UNIQUE column constraint. The default naming pattern is table_column_key for unique constraints and table_pkey for primary keys. You can choose your own name with CONSTRAINT name UNIQUE (...) when you create the table.
ON CONSTRAINT has trade-offs:
- It is explicit and cannot silently match a different index.
- It ties the query to a constraint name, so renaming the constraint breaks the query. A column list survives a rename or a rebuild of the index.
- It only works with constraints. An index created with
CREATE UNIQUE INDEXis not a constraint and has no constraint name to use. That includes partial and expression indexes.
For these reasons, most code uses the column list and keeps ON CONSTRAINT for the few cases that need it.
Partial unique indexes
A partial unique index enforces uniqueness only for rows that satisfy a WHERE condition. To use it as the arbiter, repeat that condition in the conflict target:
CREATE TABLE app_user (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL,
name text NOT NULL,
deleted_at timestamptz
);
CREATE UNIQUE INDEX app_user_email_active_idx
ON app_user (email) WHERE deleted_at IS NULL;
INSERT INTO app_user (email, name)
VALUES ('[email protected]', 'Ada')
ON CONFLICT (email) WHERE deleted_at IS NULL
DO UPDATE SET name = EXCLUDED.name;The WHERE after the column list is the index predicate. It is not a filter on which rows to update. PostgreSQL uses it only to find the right index. Without it, inference fails and you get the "no unique or exclusion constraint matching" error, because the full-table (email) target does not match a partial index.
The predicate you write must imply the index predicate. Writing the same condition is the safest choice. Also note that the proposed row itself must satisfy the predicate. A row proposed with a non-null deleted_at is outside the index and cannot conflict with it.
Expression indexes
If uniqueness is defined on an expression, such as case-insensitive email, the target must contain the same expression:
CREATE TABLE contact (
email text NOT NULL,
name text NOT NULL
);
CREATE UNIQUE INDEX contact_email_lower_idx ON contact (lower(email));
INSERT INTO contact (email, name)
VALUES ('[email protected]', 'Ada')
ON CONFLICT (lower(email)) DO UPDATE
SET name = EXCLUDED.name;Inference compares expressions structurally. lower(email) matches an index on lower(email). A different but logically equivalent expression, such as email::citext, does not. Copy the expression from the index definition.
Omitting the target
The target is optional only for DO NOTHING:
INSERT INTO account (email, handle, display_name)
VALUES ('[email protected]', 'ada', 'Grace')
ON CONFLICT DO NOTHING;Without a target, every unique index and exclusion constraint on the table is an arbiter. A duplicate on any of them skips the row. This is convenient for "insert if not already there" jobs. It also hides which rule caused the skip. The statement above skips Grace because of the handle, and nothing tells you so.
DO UPDATE always requires a target. PostgreSQL needs to know which row to update. If several unique rules could each match a different existing row, no single row is well defined.
You can also combine both styles: ON CONFLICT (email) DO NOTHING skips only email duplicates and still errors on handle duplicates.
Other restrictions
- Deferrable constraints. A unique constraint declared
DEFERRABLEcannot be an arbiter forDO UPDATE, because uniqueness would be checked at commit time, not at insert time. - NULL values. A unique index treats NULLs as distinct by default. A proposed row with
NULLin an indexed column never conflicts, so it is always inserted. PostgreSQL 15 addedUNIQUE NULLS NOT DISTINCTfor cases where NULLs should conflict. - Collations and operator classes. If the index uses a non-default collation or operator class, the target may need to specify it so inference can match.
Quick reference
| Situation | Conflict target to write |
|---|---|
| Single-column primary key or unique column | `ON CONFLICT (sku)` |
| Composite key | `ON CONFLICT (warehouse_id, sku)` |
| Expression index | `ON CONFLICT (lower(email))` |
| Partial unique index | `ON CONFLICT (email) WHERE deleted_at IS NULL` |
| Unique constraint, name is stable and known | `ON CONFLICT ON CONSTRAINT account_email_key` |
| Skip duplicates on any unique rule | `ON CONFLICT DO NOTHING` |
Choosing between forms
Use these criteria in order:
- Match the business rule. Pick the unique rule that defines "the same row" for your case. If the table has several, decide which one the upsert owns.
- Prefer a column list. It survives index rebuilds and constraint renames, and it reads like the schema.
- Use
ON CONSTRAINTwhen a column list cannot express the arbiter, or when you want a hard failure if someone drops or renames the constraint. - Use no target only with
DO NOTHING, and only when you accept silent skips on every unique rule.
Exercise
A table membership has columns org_id, user_id, role, and left_at. It has a unique index CREATE UNIQUE INDEX membership_active_idx ON membership (org_id, user_id) WHERE left_at IS NULL;. Write an INSERT of (10, 42, 'admin') that updates role when an active membership already exists. Then say why ON CONFLICT (org_id, user_id) DO UPDATE ... without a WHERE fails.
Show answer
INSERT INTO membership (orgid, userid, role) VALUES (10, 42, 'admin') ON CONFLICT (orgid, userid) WHERE leftat IS NULL DO UPDATE SET role = EXCLUDED.role; Without the WHERE, the target asks for a unique index on (orgid, user_id) over all rows. The only such index is partial, so inference finds no match and PostgreSQL raises "there is no unique or exclusion constraint matching the ON CONFLICT specification". The index predicate in the target tells PostgreSQL to use the partial index.
Exercise
A table has UNIQUE (email) and UNIQUE (handle). You run INSERT ... ON CONFLICT (email) DO NOTHING with a new email and a handle that already exists. What happens, and how would the result change if you removed the conflict target?
Show answer
The statement raises a duplicate key error on the handle constraint, because only the email index is an arbiter. With ON CONFLICT DO NOTHING and no target, all unique indexes are arbiters, so the row is skipped silently and no error is raised.