Deutsch
Error messageSupabase · Postgres

Fix “violates foreign key constraint” in Supabase, on insert and on delete

Why Supabase says insert or update violates foreign key constraint, or update or delete violates it, the usual causes, and fixes that keep your data consistent.

The message you seePostgres · 23503

insert or update on table "notes" violates foreign key constraint "notes_user_id_fkey"

By Tim GeithnerPublished 5 min read

Short answer

A foreign key makes a column point to a row in another table. On insert, the message means the row you point to does not exist: a made-up or test id, an id from another Supabase project, or a user that was deleted while their session still works. On delete, it means other rows still point to the row you are deleting, typically a user who still owns notes or a profile. Use real ids, and decide per table what happens on delete: cascade for data the user owns, set null only for optional links. Never drop the constraint to make the error go away.

Ask an AI about this page:ChatGPTClaude

On this page

A foreign key says “this column points to a row in that table”. Postgres refuses any write that would break that promise, with error code 23503. There are two versions of the message. insert or update on table ... violates foreign key constraint means the row you point to does not exist. update or delete on table ... violates foreign key constraint ... on table ... means you tried to delete a row that other rows still point to. Nothing was saved or deleted in either case.

The message names the constraint, usually table_column_fkey, so notes_user_id_fkey is the user_id column of notes. The details line under it names the value, for example Key (user_id)=(3333...) is not present in table "users". When a signed-in user hits the error, row level security hides the value and the line reads only Key is not present in table "users".

Find your cause in 30 seconds

What you seeMost likely cause
insert or update ... from a seed script, a test or a server functionThe id does not exist
insert or update ... for one user only, right after their account was deletedThe user is gone, the session is not
update or delete on table "users" ..., or “Database error deleting user” in the dashboardThe user still owns rows

All three reproduce with two small tables. We ran every message on this page on Postgres with Supabase’s roles. Note that notes.user_id has no on delete rule, which is the default and the root of cause 3:

The tables used on this page
create table public.projects (
  id uuid primary key default gen_random_uuid(),
  owner_id uuid not null default auth.uid() references auth.users (id) on delete cascade,
  name text not null
);

create table public.notes (
  id uuid primary key default gen_random_uuid(),
  user_id uuid not null default auth.uid() references auth.users (id),
  project_id uuid references public.projects (id) on delete cascade,
  body text not null
);

alter table public.projects enable row level security;
alter table public.notes enable row level security;

create policy "Users can read their projects"
  on public.projects for select to authenticated
  using ((select auth.uid()) = owner_id);
create policy "Users can add their own projects"
  on public.projects for insert to authenticated
  with check ((select auth.uid()) = owner_id);
create policy "Users can read their notes"
  on public.notes for select to authenticated
  using ((select auth.uid()) = user_id);
create policy "Users can add their own notes"
  on public.notes for insert to authenticated
  with check ((select auth.uid()) = user_id);

The three causes

1. The id does not exist

The row points to an id that is not in the other table. Typical sources in AI-built apps: a hard-coded test id, seed data that creates notes before the users they belong to, ids copied from your local or test project into production, and code that invents an id for a profile with crypto.randomUUID() instead of using the user’s id. A profile must use the id of the auth user, and the safest way to get it is a trigger on auth.users, so the profile can only exist once the user does.

Inside the browser you rarely see this for user_id: an insert policy that checks the owner refuses a foreign user_id first, with the row level security error. You do see it for other columns, such as a project_id from a list that is out of date.

2. The user is gone, the session is not

Deleting a user does not sign them out. Supabase’s docs say an access token stays valid until it expires. If the app is still open, its next insert sends the deleted user’s id, default auth.uid() fills it in, and the foreign key refuses it because the user no longer exists. That is the right outcome. Sign the user out when you delete the account, and treat this error on the owner column as “account gone”.

3. The user still owns rows

You delete a user, in the dashboard or with auth.admin.deleteUser(), and a table still points to them without an on delete rule. The default, no action, refuses the delete:

The delete variant
update or delete on table "users" violates foreign key constraint "notes_user_id_fkey" on table "notes"

The dashboard shows only Failed to delete user: Database error deleting user; the full message is in the Postgres logs. The same rule works one level down: notes.project_id cascades, so deleting a project deletes its notes. Without that rule, deleting a project with notes would fail the same way.

How to fix it

For cause 1, use ids that exist: create users before their data in seed scripts, create profiles with a trigger on auth.users, and never invent owner ids in the client. For cause 2, sign the user out after deleting the account.

For cause 3, decide per table what should happen when the user goes. First list every table that points to auth.users and its current rule:

Find every table that points to auth.users
select
  conrelid::regclass as table_name,
  conname as constraint_name,
  case confdeltype
    when 'c' then 'cascade'
    when 'n' then 'set null'
    when 'd' then 'set default'
    when 'r' then 'restrict'
    else 'no action'
  end as on_delete
from pg_constraint
where contype = 'f'
  and confrelid = 'auth.users'::regclass
order by conrelid::regclass::text;

For data the user owns, delete it with the user. When the account goes, its data goes:

SafeFix: delete a user's notes with the user
alter table public.notes
  drop constraint notes_user_id_fkey,
  add constraint notes_user_id_fkey
    foreign key (user_id) references auth.users (id) on delete cascade;

Use on delete set null only for optional links, such as assigned_to on a shared task. On a not null column it fails with the not-null error, and making an owner column nullable creates rows that belong to nobody.

SafeFix: notes only in your own projects
drop policy "Users can add their own notes" on public.notes;

create policy "Users can add notes to their own projects"
  on public.notes for insert
  to authenticated
  with check (
    (select auth.uid()) = user_id
    and (
      project_id is null
      or exists (
        select 1 from public.projects p
        where p.id = project_id and p.owner_id = (select auth.uid())
      )
    )
  );

The same pattern protects every link between tables in a multi-user app. The guide to multi-tenant data isolation and the missing ownership check fix go deeper.

Fix the foreign key error without losing integrity

My Supabase app fails with “violates foreign key constraint” (either “insert or update on table ...” or “update or delete on table ...”). First list every foreign key in the migrations, especially those that reference auth.users, with their on delete rule. Then fix it like this, in a new migration: for tables whose rows belong to a user (profiles, notes, settings), change the foreign key to auth.users to on delete cascade; use on delete set null only for optional, nullable links. Make profiles get created by a trigger on auth.users with the user’s own id, never with an id generated in the client. For every insert policy on a table that references another user-owned table, add a check that the referenced row belongs to (select auth.uid()).

Do not drop foreign keys, do not make owner columns nullable, do not move writes to the service role key and do not edit existing migrations. Show me the migration before applying it.

Check that the fix works

Run the query that lists the foreign keys again: every table with user data should show cascade. Then delete a test user inside a transaction and roll back, so nothing is lost:

Check: delete a test user and roll back
begin;
delete from auth.users where id = '11111111-1111-1111-1111-111111111111';
select count(*) as notes_left from public.notes
  where user_id = '11111111-1111-1111-1111-111111111111';
rollback;

The delete runs without an error and notes_left is 0. To check the project rule, act as one user and try to add a note to another user’s project, as in the guide to testing RLS policies: it must fail with the row level security error.

Frequently asked questions

Can I just drop the foreign key?

No. The constraint is what stops rows from pointing to nothing. Without it, notes of deleted users stay in your database forever, still holding their personal data, and your app has to cope with owners that no longer exist. Fix the id or the delete rule instead.

Why does deleting a user in the dashboard fail with Database error deleting user?

Supabase Auth hides the database error behind that message. Usually a table points to auth.users without on delete cascade, so Postgres refuses to delete a user who still owns rows. The Postgres logs show the full update or delete message with the table name.

Should I use on delete cascade or on delete set null?

Cascade for data that belongs to the user, such as notes, profiles and settings: when the account goes, the data goes. Set null for optional links, such as an assigned_to column on a team task. Set null on a not null column fails with a not-null error.

The id is in auth.users. Why do I still get the error?

Check that you are looking at the same project: ids from your local or test project do not exist in production. Also check the Key line in the error details, which names the value that was not found. If the user was just deleted, an old session can still send requests until its access token expires.

Sources

  1. 1.Constraints: Foreign Keys — PostgreSQL Documentation
  2. 2.PostgreSQL Error Codes — PostgreSQL Documentation
  3. 3.Cascade Deletes — Supabase Docs
  4. 4.Errors when creating / updating / deleting users — Supabase Docs
  5. 5.User Management — Supabase Docs
  6. 6.CREATE POLICY — PostgreSQL Documentation

Find this in your own app

ShipRely reads your repository (read-only), proves each finding with file and line, and gives you a fix prompt to paste into your AI builder.

Run a demo audit
  • Read-only access to your repository
  • Every finding with file and line
  • Fix prompts for Lovable, Cursor, Claude Code and Bolt