5

Follow up to Update multiple rows in 1 column in MySQL.

What is the most efficient query for updating multiple rows in 2 columns?

UPDATE example_table SET variable1 = 12 WHERE id=1;
UPDATE example_table SET variable2 = 'blue' WHERE id=1;

UPDATE example_table SET variable1 = 42 WHERE id=2;
UPDATE example_table SET variable2 = 'red' WHERE id=2;

UPDATE example_table SET variable1 = 32 WHERE id=3;
UPDATE example_table SET variable2 = 'yellow' WHERE id=3;

Using case seems to be the most efficient, but how would I do it with multiple values being set at one time?

4 Answers 4

11

If you have a table named categories and say two columns are display_order and title Here is what you will do :

UPDATE categories
SET display_order = CASE id
    WHEN 1 THEN 32
    WHEN 2 THEN 33
    WHEN 3 THEN 34
END,
title = CASE id
    WHEN 1 THEN 'New Title 1'
    WHEN 2 THEN 'New Title 2'
    WHEN 3 THEN 'New Title 3'
END
WHERE id IN (1,2,3)
Sign up to request clarification or add additional context in comments.

Comments

2

I think again CASE is the solution. The idea is to use separate CASE statements for each variable. Something like:

UPDATE `example_table`
SET `variable1` = (CASE
    WHEN `id` = 1 THEN 12
    WHEN `id` = 2 THEN 42
    WHEN `id` = 3 THEN 32
    END),
`variable2` = (CASE
    WHEN `id` = 1 THEN 'blue'
    WHEN `id` = 2 THEN 'red'
    WHEN `id` = 3 THEN 'yellow'
    END);

Hope it helps!

Comments

2

Some not need to put the this Sign on id ' ' eg: 'id' you can leave it blank...like

UPDATE example_table
SET variable1 = (CASE
    WHEN id = 1 THEN 12

Comments

0

Something like this could be what you want to do :

UPDATE example_table SET variable1 = 42,variable2 = 'red' WHERE id=2;

1 Comment

Thanks Aleroot, but your answer doesn't deal with updating multiple rows, just multiple columns.

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.