Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update multiple rows in 1 column in MySQL [duplicate]

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 :)

like image 868
Don P Avatar asked Feb 19 '12 04:02

Don P


1 Answers

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
like image 180
Vikram Avatar answered Oct 25 '22 16:10

Vikram