JavaScript: upsert

Perform an UPSERT on the table or view. Depending on the column(s) passed to onConflict, .upsert() allows you to perform the equivalent of .insert() if a row with the corresponding onConflict columns doesn't exist, or if it does exist, perform an alternative action depending on ignoreDuplicates.

By default, upserted rows are not returned. To return it, chain the call with .select().

Parameters

Examples

Upsert a single row using a unique key

// Upserting a single row, overwriting based on the 'username' unique column
const { data, error } = await supabase
  .from('users')
  .upsert({ username: 'supabot' }, { onConflict: 'username' })

// Example response:
// {
//   data: [
//     { id: 4, message: 'bar', username: 'supabot' }
//   ],
//   error: null
// }

Upsert with conflict resolution and exact row counting

// Upserting and returning exact count
const { data, error, count } = await supabase
  .from('users')
  .upsert(
    {
      id: 3,
      message: 'foo',
      username: 'supabot'
    },
    {
      onConflict: 'username',
      count: 'exact'
    }
  )

// Example response:
// {
//   data: [
//     {
//       id: 42,
//       handle: "saoirse",
//       display_name: "Saoirse"
//     }
//   ],
//   count: 1,
//   error: null
// }

Upsert your data

const { data, error } = await supabase
  .from('instruments')
  .upsert({ id: 1, name: 'piano' })
  .select()

Handling errors

const { data, error } = await supabase.from('instruments').upsert({ id: 1, name: 'piano' }).select()
if (error) console.error(error)

Bulk Upsert your data

const { data, error } = await supabase
  .from('instruments')
  .upsert([
    { id: 1, name: 'piano' },
    { id: 2, name: 'harp' },
  ])
  .select()

Upserting into tables with constraints

const { data, error } = await supabase
  .from('users')
  .upsert({ id: 42, handle: 'saoirse', display_name: 'Saoirse' })
  .select()