Supabase upsert: "there is no unique or exclusion constraint matching the ON CONFLICT specification"

By AI App Medic · Updated · Supabase · Postgres · Database · Lovable

A save button, an import or a "create my profile if it does not exist" step fails, and the response from Supabase looks like this:

{
  "code": "42P10",
  "details": null,
  "hint": null,
  "message": "there is no unique or exclusion constraint matching the ON CONFLICT specification"
}

The request was an upsert. In supabase-js that is .upsert(), which becomes INSERT ... ON CONFLICT (columns) DO UPDATE in Postgres. To know whether a row "already exists", Postgres needs a unique constraint or unique index on exactly the columns named in the conflict target. If none matches, it refuses to plan the statement and nothing is written.

AI builders produce this error often because they write the upsert in the front end and assume the database already enforces uniqueness. The code says onConflict: "user_id", but the migration that created the table never made user_id unique. The fix is almost always in the database, not in the JavaScript.

Step 1: read what the code asks for

Find the call. It usually looks like one of these:

// supabase-js
await supabase
  .from("user_settings")
  .upsert({ user_id: user.id, theme: "dark" }, { onConflict: "user_id" });

# supabase-py
supabase.table("products").upsert(rows, on_conflict="sku,brand_id").execute()

Write down the table and the exact list of columns in onConflict. If there is no onConflict at all, Supabase uses the primary key, which always has a unique index. In that case you will not see 42P10, but you may see a different problem, covered in Step 6.

Step 2: list the unique indexes the table really has

Open the SQL editor in the Supabase dashboard and run this, with your table name:

select
  indexrelid::regclass as index_name,
  pg_get_indexdef(indexrelid) as definition
from pg_index
where indrelid = 'public.user_settings'::regclass
  and indisunique;

Compare each definition with the columns from Step 1. The match has to be exact:

If the only result is the primary key, the constraint was never created. That is the common case.

Step 3: clean up duplicates before adding the constraint

If the table already has rows that break the rule, adding the constraint fails with could not create unique index and Key (user_id)=(...) is duplicated. Find them first:

select user_id, count(*)
from public.user_settings
group by user_id
having count(*) > 1;

Decide which row to keep for each key. Often the newest one is right, but check whether other tables point at the rows you are about to delete. Take a backup, or at least copy the table, before deleting:

create table public.user_settings_backup as
  select * from public.user_settings;

-- keep the most recently updated row per user_id
delete from public.user_settings a
using public.user_settings b
where a.user_id = b.user_id
  and (a.updated_at, a.id) < (b.updated_at, b.id);

Adjust updated_at to whatever column tells you which row is current. Run the duplicate check again and confirm it returns nothing.

Step 4: add the unique constraint

Create a constraint on exactly the columns the upsert names:

-- one column
alter table public.user_settings
  add constraint user_settings_user_id_key unique (user_id);

-- two columns together
alter table public.daily_stats
  add constraint daily_stats_user_id_date_key unique (user_id, date);

Adding a constraint locks the table while the index is built. On a small table that takes milliseconds. On a large table that is written to all the time, build the index first without blocking writes, then attach it:

create unique index concurrently daily_stats_user_id_date_idx
  on public.daily_stats (user_id, date);

alter table public.daily_stats
  add constraint daily_stats_user_id_date_key
  unique using index daily_stats_user_id_date_idx;

create index concurrently cannot run inside a transaction, so run it as its own statement. If you use migrations (the Supabase CLI or a Lovable migration), put the constraint in a migration file so the next environment gets it too. A constraint added by hand in production and missing from the migrations is how this error comes back on the staging project or after a database reset.

Step 5: write onConflict correctly

With the constraint in place, name the columns as a single comma-separated string:

const { data, error } = await supabase
  .from("daily_stats")
  .upsert(
    { user_id: user.id, date: "2026-11-29", visits: 42 },
    { onConflict: "user_id,date" }
  )
  .select();

Passing an array, onConflict: ["user_id", "date"], is a common mistake in generated code. It is not the documented format. Use the string. The same applies in Python: on_conflict="user_id,date".

If you only want to insert new rows and leave existing ones alone, add ignoreDuplicates: true. That becomes ON CONFLICT DO NOTHING, which also needs the matching unique constraint.

Step 6: the related upsert problems

Upsert silently inserts duplicates

No error, but every save adds a new row. The code has no onConflict, so Supabase matches on the primary key, and the payload either has no id or a freshly generated one. Every row looks new. Add onConflict with the real unique columns and the constraint from Step 4. A typical Lovable case is a profiles table whose primary key id is the user's id: upsert with onConflict: "id" and send id: user.id, instead of inventing a separate user_id column with no constraint.

ON CONFLICT DO UPDATE command cannot affect row a second time

Code 21000. A bulk upsert contains two rows with the same conflict key, so one statement would update the same row twice. This happens with CSV imports and with arrays built from an API that repeats items. Deduplicate before sending, keeping the last value for each key:

const byKey = new Map();
for (const row of rows) byKey.set(`${row.user_id}|${row.date}`, row);
const unique = [...byKey.values()];

await supabase.from("daily_stats").upsert(unique, { onConflict: "user_id,date" });

Rows with NULL never conflict

By default Postgres treats NULL values as different from each other, so a unique constraint on (title, venue) lets you insert the same title twice if venue is NULL, and the upsert inserts instead of updating. On Postgres 15 and later, which current Supabase projects run, you can make NULLs count as equal:

alter table public.papers
  add constraint papers_title_venue_key unique nulls not distinct (title, venue);

Check your version with select version(); before you rely on it.

You need a partial or case-insensitive unique rule

Soft deletes (unique where deleted_at is null) and case-insensitive emails (unique (lower(email))) are real requirements, but supabase-js cannot target those indexes. Two clean options:

create or replace function public.subscribe(p_email text, p_list text)
returns void
language sql
security invoker
set search_path = ''
as $$
  insert into public.subscribers (email, list)
  values (lower(p_email), p_list)
  on conflict (email, list) where deleted_at is null
  do nothing;
$$;
await supabase.rpc("subscribe", { p_email: email, p_list: "news" });

security invoker keeps your row level security policies in force for the caller. Do not switch it to security definer to make an error go away.

new row violates row-level security policy

Once the constraint exists, the next error is often an RLS one. An upsert may insert or update, so the user needs both an INSERT and an UPDATE policy on the table, and a SELECT policy if you chain .select(). The policies and checks are covered in new row violates row-level security policy.

Why the upsert matters more than the error

Generated code often avoids upsert and does "select, then insert if nothing came back" instead. That works in testing and breaks under real use: two tabs, a double click or a retry run both selects before either insert, and you end up with two profile rows. Later, .single() starts failing with JSON object requested, multiple (or no) rows returned. A unique constraint plus an upsert closes that race inside the database. The same applies to a signup trigger that creates a profile row: give it a unique key and on conflict do nothing, or a retried signup can fail with Database error saving new user.

Prevention

Every time code says "one per", such as one settings row per user, one stats row per user per day, or one product per SKU, write a unique constraint in the same migration that creates the table. Before shipping an upsert, run the pg_index query from Step 2 against the target table and confirm the conflict columns appear in one unique definition. Keep constraints in migrations, not only in the dashboard, so staging and production match. When you ask an AI tool to add an upsert, ask it to show the constraint it relies on, and check that the constraint is in a migration file.

FAQ

What does there is no unique or exclusion constraint matching the ON CONFLICT specification mean?

Postgres error 42P10 means the upsert told the database to detect duplicates on a set of columns, and the table has no unique constraint or unique index on exactly that set. Postgres checks this before inserting anything, so no rows were written.

How do I upsert on two columns in Supabase?

Add a unique constraint on both columns together, for example UNIQUE (user_id, date), then call upsert(rows, { onConflict: 'user_id,date' }). The value is one string with the column names separated by commas, not an array.

Why does upsert insert duplicate rows instead of updating?

Without onConflict, Supabase matches on the primary key. If your payload has no id, or a new generated id each time, every row looks new and is inserted. Name the real unique columns in onConflict and make sure a unique constraint exists on them.

Can I use a partial unique index with Supabase upsert?

Not directly. Postgres only uses a partial index when the ON CONFLICT clause repeats its WHERE condition, and supabase-js has no way to send that condition. Use a full unique index, NULLS NOT DISTINCT if NULL values are the reason for the partial index, or write the upsert in a SQL function and call it with rpc().

What does ON CONFLICT DO UPDATE command cannot affect row a second time mean?

Your batch contains two or more rows with the same conflict key, so Postgres would update the same row twice in one statement. Remove duplicates from the array before calling upsert(), keeping the last value for each key.

Does upsert need special RLS policies?

Yes. An upsert can insert or update, so the table needs an INSERT policy and an UPDATE policy for the user. If you chain .select(), it also needs a SELECT policy. Missing policies give new row violates row-level security policy, not 42P10.

Related guides