JavaScript: Upsert data
- Primary keys should be included in the data payload in order for an update to work correctly.
- Primary keys must be natural, not surrogate. There are however, workarounds for surrogate primary keys.
- If you need to insert new data and update existing data at the same time, use Postgres triggers.
Examples
Upsert your data
const { data, error } = await supabase
.from('messages')
.upsert({ id: 3, message: 'foo', username: 'supabot' })
Bulk Upsert your data
const { data, error } = await supabase
.from('messages')
.upsert([
{ id: 3, message: 'foo', username: 'supabot' },
{ id: 4, message: 'bar', username: 'supabot' }
])
Upserting into tables with constraints
const { data, error } = await supabase
.from('users')
.upsert({ username: 'supabot' }, { onConflict: 'username' })
Return the exact number of rows
const { data, error, count } = await supabase
.from('users')
.upsert({
id: 3, message: 'foo',
username: 'supabot'
}, {
count: 'exact'
})