Incident Response

PostgreSQL: there is no unique or exclusion constraint matching the ON CONFLICT specification

Your upsert names columns that no valid unique index covers exactly. Here is how PostgreSQL picks the arbiter index, the six usual reasons it finds none, and how to add the missing index on a large, busy table.

· 16 min read · AG Data Team

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:

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

  1. 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.
  2. The column set does not match. The index is UNIQUE (tenant_id, email) but the statement says ON CONFLICT (email), or the other way round. PostgreSQL will not use a wider or narrower index. List exactly the key columns of the index.
  3. The index is on an expression. A case-insensitive index such as UNIQUE (lower(email)) only matches ON CONFLICT ((lower(email))), with the expression written the same way.
  4. The index is partial. A soft-delete pattern like UNIQUE (email) WHERE deleted_at IS NULL needs the predicate in the statement: ON CONFLICT (email) WHERE deleted_at IS NULL.
  5. The index is invalid. A CREATE UNIQUE INDEX CONCURRENTLY that 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.
  6. You are looking at a different table. A different search_path or 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

-- 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:

Key takeaways

PostgreSQL Errors Indexes Upsert
Work with us

Upserts failing after a release?

We review PostgreSQL schemas, unique indexes and upsert patterns, and add missing constraints to large production tables without downtime.

Get in touch More from the blog