SQL - Update multiple records in one query

user3022527 picture user3022527 · Nov 28, 2013 · Viewed 632.6k times · Source

I have table - config. Schema: config_name | config_value

And I would like to update multiple records in one query. I try like that:

UPDATE config 
SET t1.config_value = 'value'
  , t2.config_value = 'value2' 
WHERE t1.config_name = 'name1' 
  AND t2.config_name = 'name2';

but that query is wrong :(

Can you help me?

Answer

peterm picture peterm · Nov 28, 2013

Try either multi-table update syntax

UPDATE config t1 JOIN config t2
    ON t1.config_name = 'name1' AND t2.config_name = 'name2'
   SET t1.config_value = 'value',
       t2.config_value = 'value2';

Here is SQLFiddle demo

or conditional update

UPDATE config
   SET config_value = CASE config_name 
                      WHEN 'name1' THEN 'value' 
                      WHEN 'name2' THEN 'value2' 
                      ELSE config_value
                      END
 WHERE config_name IN('name1', 'name2');

Here is SQLFiddle demo