© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
SupabaseS
Supabase•4y ago•
6 replies
BoogersLLC

Foreign Key Fails on Trigger

I'm having an issue when I create a new user, I want to insert a row (using a trigger) into the
decks
decks
table, which has a foreign key constraint of
user_id
user_id
.

I get this error:
insert or update on table "decks" violates foreign key constraint "decks_user_id_fkey"
insert or update on table "decks" violates foreign key constraint "decks_user_id_fkey"


However, as seen in the snippet below, I believe I am passing this value in as
new.id
new.id
to the field
user_id
user_id


Is there a way I can log the value of
new.id
new.id
? Or am I doing something obviously incorrect here?

What I've tried: I tested the insert in isolation using hardcoded data, tested the function / trigger with mock examples. It just seems to be when I try to pass the
new.id
new.id
to real data with real constraints that it fails.

create or replace function public.handle_new_user()
returns trigger
language plpgsql
security definer set search_path = public
as $$
DECLARE
  deckId uuid := gen_random_uuid();
begin
  insert into public.decks(id, description, title, user_id)
  values (deckId, 'test', 'test', new.id);
  return new;
end;
$$;

create trigger on_user_created
  after insert on public.cards
  for each row execute procedure public.handle_new_user();
create or replace function public.handle_new_user()
returns trigger
language plpgsql
security definer set search_path = public
as $$
DECLARE
  deckId uuid := gen_random_uuid();
begin
  insert into public.decks(id, description, title, user_id)
  values (deckId, 'test', 'test', new.id);
  return new;
end;
$$;

create trigger on_user_created
  after insert on public.cards
  for each row execute procedure public.handle_new_user();
Supabase banner
SupabaseJoin
Supabase gives you the tools, documentation, and community that makes managing databases, authentication, and backend infrastructure a lot less overwhelming.
45,816Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

Composite key foreign key issue
SupabaseSSupabase / help-and-questions
6mo ago
violates foreign key constraint
SupabaseSSupabase / help-and-questions
4y ago
Foreign Key Array Columns
SupabaseSSupabase / help-and-questions
4y ago
Joining auth.user on foreign key id?
SupabaseSSupabase / help-and-questions
4y ago