© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
SupabaseS
Supabase•3y ago•
13 replies
Dirk

Auto-Generating Unique Usernames in Supabase Trigger Function Not Working

Hello everyone,

I'm working on a project using Supabase and I've run into an issue with a trigger function designed to auto-generate unique usernames for new users. I would greatly appreciate any insights or assistance in resolving this problem.

Here's the situation:

Goal: Automatically create a unique username in the format "player#<number>" for each new user who signs up.
Problem: The trigger function I wrote isn't generating unique usernames as intended. It seems the logic meant to increment the count for each new user is not functioning correctly.
Current Approach:
create function public.handle_new_user () returns trigger as $$
declare
  row_count int;
  row_count_text text;
begin
  -- get the current row count
  -- select count(*) into row_count from profiles;

  -- Increment the row count for the new username
  row_count := row_count + 1;
  row_count_text := row_count::text;

  insert into public.profiles (id, username)
  values (new.id, ('player#' || row_count_text));
  return new;
end;
$$ language plpgsql security definer;
create function public.handle_new_user () returns trigger as $$
declare
  row_count int;
  row_count_text text;
begin
  -- get the current row count
  -- select count(*) into row_count from profiles;

  -- Increment the row count for the new username
  row_count := row_count + 1;
  row_count_text := row_count::text;

  insert into public.profiles (id, username)
  values (new.id, ('player#' || row_count_text));
  return new;
end;
$$ language plpgsql security definer;


Questions:
- How can I modify this function to ensure each username is unique and follows the desired format?
- Are there better approaches or best practices for achieving this in a Supabase environment?
- How can I debug this to see what's going wrong during the trigger execution?
Any advice, code snippets, or resources would be incredibly helpful. I'm relatively new to using Supabase and triggers, so detailed explanations would be greatly appreciated.

Thank you in advance for your time and help!
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
Was this page helpful?

Similar Threads

Recent Announcements

Similar Threads

supabase function deploy not working
SupabaseSSupabase / help-and-questions
4y ago
supabase.auth.setSession() not working in serverless function
SupabaseSSupabase / help-and-questions
4y ago
Trigger not working or function not firing—RLS?
SupabaseSSupabase / help-and-questions
4y ago
Invoking an edge function via Supabase trigger/function
SupabaseSSupabase / help-and-questions
3y ago