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.


Discover more from Coursity

Subscribe to get the latest posts sent to your email.

Leave a Comment

Your email address will not be published. Required fields are marked *

Discover more from Coursity

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top
Famous military generals in korean history 한국 역사 속 유명 군장.