![](https://i0.wp.com/media.dev.to/cdn-cgi/image/width=1000,height=500,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe6tpjq9riv0kn58l3e3y.png?w=1200&ssl=1)
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);
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.