7

I looking to update multiple rows via a single query in Supabase. I'm struggling to find an example of how to do it online.

For this example here is how the data exists the database's 'food' table:

id title qty
1 Apple 10
2 Banana 8
3 Mango 4

What i would like to do is update the 3 qty fields in the single query (this code doesn't work but should give you an idea of what i am after).

const { data: item_data, error: item_error } = await supabase
   .from('food')
   .update({ qty: 11, }).eq('id', '1')
   .update({ qty: 9, }).eq('id', '2')
   .update({ qty: 6, }).eq('id', '3')
1

2 Answers 2

15

You can do it with an upsert():

const { data, error } = await supabase
  .from('food')
  .upsert([{id: 1, qty: 11}, {id: 2, qty: 9}, {id: 3, qty: 6}])

Additionally you can also do it with a SQL function as mentioned here.

Sign up to request clarification or add additional context in comments.

Comments

-1

Actually, the .update function does not work when you do it like that. You can run it synchronously to update those values. Here is my solution; it works for me now!

try {
  const mappings = [
    { qty: 11, id: '1'},
    { qty: 9, id: '2'},
    { qty: 6, id: '3'},
  ]
  for (const mapping of mappings) {
    const { ref, value } = mapping
    
    const { data, error } = await supabase
      .from('food')
      .update({ qty: value }) 
      .eq('id', ref)  value

    if (error) throw error
    console.log(`Updated ${ref} to ${value}`)
  }
} catch (error) {
  console.error('Error during update process:', error)
}

1 Comment

this is incredibly inefficient as you are firing an individual request to supabase for every entry in the mappings array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.