8

What is the proper query for updating multiple rows in MySQL at the same time?

I am only updating 1 column:

UPDATE example_table SET variable1 = 12 WHERE id=1;
UPDATE example_table SET variable1 = 42 WHERE id=2;
UPDATE example_table SET variable1 = 32 WHERE id=3;
UPDATE example_table SET variable1 = 51 WHERE id=4;

This seems like it may be inefficient, or if it is the most efficient query let me know :)

Don P
  • 60,113
  • 114
  • 300
  • 432

4 Answers4

14

you can use cases like below:

UPDATE example_table
   SET variable1 = CASE id
                     WHEN 1 THEN 12
                     WHEN 2 THEN 42
                     WHEN 3 THEN 32
                     WHEN 4 THEN 51
                   END
 WHERE id BETWEEN 1 AND 4
OMG Ponies
  • 325,700
  • 82
  • 523
  • 502
Vikram
  • 8,235
  • 33
  • 47
  • Is that actual SQL code? what is 'case' and 'id'? Does case refer to the value i want to input (e.g. 12 for the first line) and id refers to its id (e.g. 1 for the first line?) – Don P Feb 19 '12 at 04:45
  • 2
    @DonnyP: Yes, that's valid SQL - check the [CASE documentation](http://dev.mysql.com/doc/refman/5.0/en/case-statement.html) – OMG Ponies Feb 19 '12 at 04:46
3

Not applicable to your example, but you probably will find this useful:

UPDATE table
SET value = <value>
WHERE field = <specific value>

This way you can update one field in a table on the basis of another field in the same table. All the applicable rows will be updated. To quote an example which I used at work earlier this morning

UPDATE porderitems
SET currency = -2
WHERE ord = 40396

This query update the porderitems table (purchase order lines), setting the currency to -2 for all the lines connected to purchase order 40396. The query neither knows nor cares how many lines there are in that purchase order; all of them will be updated.

No'am Newman
  • 6,395
  • 5
  • 38
  • 50
0

UPDATE personal_details SET country_id= 6 where id between 26 and 40. I think this code would work if the new value is same and it needs to update in multiple rows.

Sk Arka
  • 1
  • 1
0

if your values are from another table:

UPDATE example_table
JOIN values_table ON values_table.id = example_table.id
SET example_table.variable1 = values_table.value
J Cooper
  • 4,828
  • 3
  • 36
  • 39