ERROR: there is no unique or exclusion constraint matching the ON CONFLICT specification means PostgreSQL could not find a unique index that matches the columns in your ON CONFLICT (...) clause. It is not a data problem, and no row was written. The statement is rejected while it is being planned, before any row is checked. The error is SQLSTATE 42P10 (invalid_column_reference).
INSERT INTO users (tenant_id, email, name)
VALUES (42, 'ana@example.com', 'Ana')
ON CONFLICT (email) DO UPDATE SET name = EXCLUDED.name;
ERROR: there is no unique or exclusion constraint matching the ON CONFLICT specification
Developers usually hit this right after a migration, and the confusing part is that the column is often "unique" in their head, or even in another environment. To fix it you need to know how PostgreSQL matches the clause against indexes, because the rule is stricter than most people expect.
How PostgreSQL picks the arbiter index
The column list after ON CONFLICT is called the conflict target. PostgreSQL does not look for a constraint with that name. It runs unique index inference. The INSERT documentation says that every unique index which, without regard to order, contains exactly the listed columns or expressions is chosen as an arbiter. The planner code that does this (infer_arbiter_indexes) adds the details:
- The index must be unique. A plain, non-unique index on the same column never counts.
- The index must be valid. An index with
indisvalid = falseis skipped. - The set of key columns must be equal to the set you listed: not a subset, not a superset. Order does not matter. Columns in an
INCLUDEclause are not key columns and are ignored. - Expression columns must match the index expressions, and every expression in the index must appear in the clause.
- For a partial index, the index predicate must be implied by the
WHEREyou give in the conflict target. - Exclusion constraints, including
WITHOUT OVERLAPSunique constraints, are skipped by inference. They can only be named withON CONFLICT ON CONSTRAINT, and even then not withDO UPDATE.
If no index passes all of these checks, you get the error. ON CONFLICT DO NOTHING with no conflict target skips inference completely, which is why it "works" while the DO UPDATE version of the same statement fails.
Step 1: look at the indexes that actually exist
Run this on the same database and schema that the failing application uses, not on your laptop:
SELECT i.indexrelid::regclass AS index_name,
i.indisunique AS is_unique,
i.indisvalid AS is_valid,
i.indimmediate AS not_deferrable,
pg_get_indexdef(i.indexrelid) AS definition
FROM pg_index i
WHERE i.indrelid = 'public.users'::regclass
ORDER BY 1;
Compare each definition with your ON CONFLICT list. In our experience the cause is one of the following six.
The six usual causes
- There is no unique index. Only a normal index exists, or the unique constraint was written in an ORM model but its migration never ran on this database. Check the migration history of the exact environment that fails.
- The column set does not match. The index is
UNIQUE (tenant_id, email)but the statement saysON CONFLICT (email), or the other way round. PostgreSQL will not use a wider or narrower index. List exactly the key columns of the index. - The index is on an expression. A case-insensitive index such as
UNIQUE (lower(email))only matchesON CONFLICT ((lower(email))), with the expression written the same way. - The index is partial. A soft-delete pattern like
UNIQUE (email) WHERE deleted_at IS NULLneeds the predicate in the statement:ON CONFLICT (email) WHERE deleted_at IS NULL. - The index is invalid. A
CREATE UNIQUE INDEX CONCURRENTLYthat failed, for example on duplicate values, leaves an index that psql shows as INVALID. It still exists and still slows down writes, but inference ignores it. - You are looking at a different table. A different
search_pathor a same-named table in another schema. Use the schema-qualified name in both the query above and the statement.
Naming an index does not work. ON CONFLICT ON CONSTRAINT only accepts constraint names. If you created a unique index with CREATE UNIQUE INDEX, there is no constraint with that name, and PostgreSQL answers constraint "..." for table "..." does not exist. The documentation recommends inference over naming a constraint anyway, because inference keeps working when the index is replaced by an equivalent one.
Step 2: fix the statement or add the index
If a suitable unique index exists, change the conflict target so it matches it:
-- unique index on (tenant_id, email): name both columns, order does not matter
ON CONFLICT (email, tenant_id) DO UPDATE ...
-- unique index on lower(email): repeat the expression, in its own parentheses
ON CONFLICT ((lower(email))) DO UPDATE ...
-- partial unique index ... WHERE deleted_at IS NULL: repeat the predicate
ON CONFLICT (email) WHERE deleted_at IS NULL DO UPDATE ...
If the uniqueness rule really does not exist yet, add it. On a small table a plain CREATE UNIQUE INDEX is fine. On a large production table, do it in steps. First check that no duplicates already exist, otherwise the build fails, just as an insert of a duplicate fails with the error described in our article on duplicate key value violates unique constraint:
-- 1. find the duplicates that would block a unique index
SELECT tenant_id, email, count(*)
FROM users
GROUP BY tenant_id, email
HAVING count(*) > 1
ORDER BY count(*) DESC
LIMIT 50;
Then build the index concurrently, confirm it is valid and, if you want a named constraint, attach the index to one:
-- 2. build the index without blocking writes (not inside a transaction block)
CREATE UNIQUE INDEX CONCURRENTLY users_tenant_email_uq
ON users (tenant_id, email);
-- 3. make sure it is valid: a failed concurrent build leaves an INVALID index behind
SELECT indexrelid::regclass, indisvalid
FROM pg_index
WHERE indexrelid = 'users_tenant_email_uq'::regclass;
-- 4. optional: turn it into a named constraint (fast, plain column index only)
ALTER TABLE users
ADD CONSTRAINT users_tenant_email_uq UNIQUE USING INDEX users_tenant_email_uq;
According to the ALTER TABLE documentation, ADD CONSTRAINT ... UNIQUE USING INDEX is a fast operation, but it only accepts a plain b-tree index with default sort order: no expression columns and no partial index. For expression and partial indexes, keep the unique index without a constraint. Inference works the same either way.
Related errors that look similar
ON CONFLICT does not support deferrable unique constraints/exclusion constraints as arbiters: the matching constraint isDEFERRABLE. OnlyNOT DEFERRABLEconstraints and unique indexes can be arbiters.ON CONFLICT DO UPDATE not supported with exclusion constraints: you named an exclusion constraint withON CONSTRAINTand usedDO UPDATE.ON CONFLICT DO UPDATE command cannot affect row a second time: the index matched, but the same key appears twice in one statement. This is common in batch loads. De-duplicate the batch first:
-- de-duplicate the batch itself before the upsert
INSERT INTO users (tenant_id, email, name)
SELECT DISTINCT ON (tenant_id, email) tenant_id, email, name
FROM staging_users
ORDER BY tenant_id, email, updated_at DESC
ON CONFLICT (tenant_id, email) DO UPDATE SET name = EXCLUDED.name;
NULLs: the upsert that silently inserts duplicates
By default a unique index treats NULLs as distinct, so a row whose key contains a NULL never conflicts with anything. ON CONFLICT will not raise an error in this case. It will simply insert another row, every time. If a NULL in the key is meant to be "one value", PostgreSQL 15 and later support UNIQUE NULLS NOT DISTINCT. On older versions, make the column NOT NULL with a default, or use an expression index such as coalesce(col, '') and the same expression in the conflict target.
What changes on large databases and fleets
On a test database with a few thousand rows, every step above takes seconds. On a table with hundreds of millions of rows that receives writes all day, the same fix needs planning:
- The duplicate check is itself a heavy query. A
GROUP BYover the whole table reads all of it and may spill to disk. In our experience it is safer to run it on a replica or in key ranges, and to fix duplicates in small batches with a clear rule for which row survives. - A concurrent build is slow and can fail late. The documentation explains that
CONCURRENTLYscans the table twice and waits for existing transactions that could use the index. A long-running transaction delays it, and a duplicate value in the table makes it fail and leave anINVALIDindex. Drop that index and retry, or rebuild it as described in our REINDEX CONCURRENTLY guide. Add a check for invalid indexes to your deploy pipeline. - Keep the old upsert working during the change. The PostgreSQL source notes that while a concurrent index operation is running, different transactions may see different sets of arbiter indexes, which can cause false unique violations. Do the index change in a quiet period, and release the code that relies on the new index only after the index is valid.
- Partitioned tables have extra rules. A unique constraint on a partitioned table must include all partition key columns, so
ON CONFLICT (id)on a table partitioned bycreated_atcan never be satisfied. Your conflict target has to include the partition key.CREATE INDEX CONCURRENTLYis not supported on the partitioned parent. Build the index concurrently on each partition, then create the parent index, which is then only a metadata change. Also,DO UPDATEcannot change the partition key in a way that moves the row to another partition. - Logical replicas do not get your DDL. Logical replication does not replicate schema changes. If the same upsert runs against a subscriber, for example after a migration cut-over, the unique index must be created there too. Physical streaming replicas receive the index through WAL.
- Schema drift across shards and tenants. In our experience, when the same schema lives in many databases, one of them is always missing a migration. Run the index query above on every database before you ship code that depends on a new conflict target, and alert on SQLSTATE
42P10in the logs right after each release.
Key takeaways
- The conflict target must match the key columns of a valid, unique, non-deferrable index exactly. Order does not matter, but subsets and supersets do not count.
- Expression and partial unique indexes need the same expression or predicate in the
ON CONFLICTclause. - A failed concurrent build leaves an
INVALIDindex that inference ignores. ON CONSTRAINTtakes constraint names only, not index names. Prefer inference.- On big tables: find duplicates first, build with
CONCURRENTLY, checkindisvalid, and remember partition keys, logical replicas and every shard.