DEV Community

Mark Woollen
Mark Woollen

Posted on β€’ Edited on

4

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.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

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.

πŸ‘‹ Kindness is contagious

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

Okay