DEV Community

sugiarto
sugiarto

Posted on

Create supabase database function

Two days ago, I had a requirement to create a database function that accepts a single argument, in this case a 'user_id', and returns custom data as a table.

To create this function, we need to open SQL Editor.

sql editor

Here is the sample code that I used at my function:

create or replace function get_friends(user_id uuid)
 RETURNS TABLE(
    friend_id uuid,
    updated_at timestamptz,
    first_name text,
    last_name text,
    email text,
    profile_image_url text,
    location text
  )
  language plpgsql as
$$

BEGIN
  RETURN QUERY
  select
    friends.friend_id,
    friends.updated_at,
    users.first_name,
    users.last_name,
    users.email,
    users.profile_image_url,
    users.location
  from friends
  inner join users ON users.id = friends.friend_id
  where
    friends.user_id = get_friend_ids.user_id AND
    friend_status = 'approved' AND
    users.info_complete = true

  union

  select
    friends.user_id friend_id,
    friends.updated_at,
    users.first_name,
    users.last_name,
    users.email,
    users.profile_image_url,
    users.location
  from friends
  inner join users ON users.id = friends.user_id
  where
    friends.friend_id = get_friends.user_id AND
    user_status = 'approved' AND
    users.info_complete = true;
end;
$$;

Enter fullscreen mode Exit fullscreen mode

As I want to function to return a custom table, so I used table as return values.

RETURNS TABLE(
    friend_id uuid,
    updated_at timestamptz,
    first_name text,
    last_name text,
    email text,
    profile_image_url text,
    location text
  )
Enter fullscreen mode Exit fullscreen mode

To call this function within a SQL editor.

select * from get_friends(uuid('e7839548-40e8-4c7e-8f6c-2b5cee6bde2d'))
Enter fullscreen mode Exit fullscreen mode

We used uuid() to convert from text to uuid.

Hope this helps.

API Trace View

Struggling with slow API calls? 👀

Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more →

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay