patternsqlModerate
Updating multiple rows with different values in one query
Viewed 0 times
rowswithupdatingquerydifferentonemultiplevalues
Problem
I am trying to understand how to UPDATE multiple rows with different values and I just don't get it. The solution is everywhere but to me it looks difficult to understand.
For instance, two updates into 1 query:
I don't understand what the CASE WHEN .. THEN ... END works and how to use it.
Wonder if someone could help me on this.
For instance, two updates into 1 query:
UPDATE mytable SET fruit='orange', drink='water', food='pizza' WHERE id=1;
UPDATE mytable SET fruit='strawberry', drink='wine', food='fish' WHERE id=2;I don't understand what the CASE WHEN .. THEN ... END works and how to use it.
Wonder if someone could help me on this.
Solution
UPDATE mytable SET
fruit = CASE WHEN id=1 THEN 'orange' ELSE 'strawberry' END,
drink = CASE WHEN id=1 THEN 'water' ELSE 'wine' END,
food = CASE WHEN id=1 THEN 'pizza' ELSE 'fish' END
WHERE id IN (1,2);Personally, using
CASE WHEN THEN END looks clumsy.You could code this using the IF function.
UPDATE mytable SET
fruit = IF(id=1,'orange','strawberry'),
drink = IF(id=1,'water','wine'),
food = IF(id=1,'pizza','fish')
WHERE id IN (1,2);Give it a Try !!!
CAVEAT :
CASE WHEN THEN END is only handy when dealing with multiple values (more than 2)Code Snippets
UPDATE mytable SET
fruit = CASE WHEN id=1 THEN 'orange' ELSE 'strawberry' END,
drink = CASE WHEN id=1 THEN 'water' ELSE 'wine' END,
food = CASE WHEN id=1 THEN 'pizza' ELSE 'fish' END
WHERE id IN (1,2);UPDATE mytable SET
fruit = IF(id=1,'orange','strawberry'),
drink = IF(id=1,'water','wine'),
food = IF(id=1,'pizza','fish')
WHERE id IN (1,2);Context
StackExchange Database Administrators Q#69269, answer score: 15
Revisions (0)
No revisions yet.