Shivam Sahil
Shivam Sahil

Reputation: 4925

Supabase update with incrementing value

I am using supabase-js and have a table like this:

userID: string
timesVisited: number
eventName: string

I am using update like this:

Admin.from(tableName).update([{userID,eventName,timesVisited}])

Currently I have to make two calls one to get current timesViewed and then update it I was interested in knowing if there's a way I could directly increment the value instead of making 2 calls?

Upvotes: 2

Views: 5059

Answers (1)

Andrew Smith
Andrew Smith

Reputation: 1841

You would do this using a Postgres function and the .rpc method of the supabase-js library.

Create a function using the SQL editor

create function increment (x int, row_id int) 
returns void as
$$
  update table_name 
  set column_name = column_name + x
  where id = row_id
$$ 
language sql volatile;

And call it like:

const { data, error } = await supabase
  .rpc('increment', { x: 1, row_id: 2 })

Upvotes: 5

Related Questions