Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update multiple records in SQL

How can i update multiple records in a single statement like this with SQL?:

UPDATE records
   SET name='abc' where id=3,
   SET name='def' where id=1
like image 222
hhh3112 Avatar asked Apr 25 '11 12:04

hhh3112


People also ask

Can you update multiple records in SQL?

In SQL, sometimes we need to update multiple records in a single query. We will use the UPDATE keyword to achieve this. For this, we use 2 kinds of examples i.e. the first based on only one condition and the second based on multiple conditions.

How can I update multiple values in one column in SQL?

First, specify the table name that you want to change data in the UPDATE clause. Second, assign a new value for the column that you want to update. In case you want to update data in multiple columns, each column = value pair is separated by a comma (,). Third, specify which rows you want to update in the WHERE clause.

How do you add multiple update statements in SQL?

The UPDATE statement in SQL is used to update the data of an existing table in database. We can update single columns as well as multiple columns using UPDATE statement as per our requirement. UPDATE table_name SET column1 = value1, column2 = value2,...


2 Answers

Standard SQL:2003 syntax (works on SQL Server 2008 onwards):

MERGE INTO records 
   USING (
          VALUES (1, 'def'), 
                 (3, 'abc')
         ) AS T (id, name)
      ON records.id = T.id
WHEN MATCHED THEN
   UPDATE 
      SET name = T.name;

Note that NAME and RECORDS are SQL reserved words.

like image 150
onedaywhen Avatar answered Sep 22 '22 21:09

onedaywhen


For just a few records, you could use:

update records
set name = case id
  when 1 then 'def'
  when 3 then 'abc'
end
where id in (1, 3)

A bit more flexible is to create a result that you can join into the update:

update r
set name = x.name
from records r
inner join (
  select id = 1, name = 'abc' union all
  select 3, 'def' union all
  select 4, 'qwe' union all
  select 6, 'rty'
) x on x.id = r.id
like image 40
Guffa Avatar answered Sep 20 '22 21:09

Guffa