DEV Community

Mark Woollen
Mark Woollen

Posted on • Edited on

Supabase UPSERT

UPSERT in Supabase is intended to be a simplified combination of UPDATE and INSERT. (If the record already exists, then it will be updated and if not, then one will be created).

However, for me, UPSERT was a bit tricky to understand and get working. Suppose I have a table ('the_table') with primary keys: 'id' (type: uuid, default: gen_random_uuid()) and 'name' (type: text). The standard documentation indicates using "onConflict" but does not provide any useful example. I managed to find an article on restack.io that had a brief code snippet buried in several pages down. I adjusted to show how onConflict can reference the 'name' column.

const { data: retData, error: retError } = await supabase
  .from('the_table')
  .upsert({ name: 'Pablo', description: 'Helpful and friendly'}, { onConflict: 'name' }).select();
console.log("Error: ", retError )
  console.log("Data: ", retData[0].name, ", ", retData[0].description);
Enter fullscreen mode Exit fullscreen mode

This snippet shows how to UPSERT a record into 'the_table' where the conflict resolution is based on the 'name' column. If a record with name ('Pablo') exists, then it will be updated; otherwise, a new record will be inserted.

NEW NOTE 9/21/2024: you can also configure "NAME" table as primary key and eliminate "ID" as primary key.

Top comments (1)

Collapse
 
spaghetticoderyyz profile image
Marc LP

Thanks 🙏 ! I basically gave up on upsert - I have a similar scenario. Cheers

Some comments may only be visible to logged-in visitors. Sign in to view all comments.