Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL CASE to update multiple columns

Tags:

sql

mysql

case

I would like to update multiple columns in my table using a case statement, but I cannot find how to do this (is this even possible). I came up with the following invalid reference query:

UPDATE tablename SET     CASE name         WHEN 'name1' THEN col1=5,col2=''         WHEN 'name2' THEN col1=3,col2='whatever'         ELSE col1=0,col2=''     END; 

Is there any way of achieving the expected result with valid SQL?

like image 277
Villermen Avatar asked Dec 02 '12 21:12

Villermen


People also ask

How UPDATE multiple rows of multiple columns in SQL?

First, specify the table name that you want to change data in the UPDATE clause. Second, assign a new value for the column that you want to update. In case you want to update data in multiple columns, each column = value pair is separated by a comma (,). Third, specify which rows you want to update in the WHERE clause.

How do you UPDATE multiple columns in SQL with different conditions?

To update multiple columns use the SET clause to specify additional columns. Just like with the single columns you specify a column and its new value, then another set of column and values. In this case each column is separated with a column.

How UPDATE multiple values in multiple rows in SQL?

There are a couple of ways to do it. INSERT INTO students (id, score1, score2) VALUES (1, 5, 8), (2, 10, 8), (3, 8, 3), (4, 10, 7) ON DUPLICATE KEY UPDATE score1 = VALUES(score1), score2 = VALUES(score2);

How do you write an UPDATE statement in a case statement?

The CASE expression allows a statement to return one of several possible results, depending on which of several condition tests evaluates to TRUE. You must include at least one WHEN clause within the CASE expression; subsequent WHEN clauses and the ELSE clause are optional.


2 Answers

UPDATE tablename SET col1 = CASE WHEN name = 'name1' THEN 5                  WHEN name = 'name2' THEN 3                  ELSE 0             END  , col2 = CASE WHEN name = 'name1' THEN ''                 WHEN name = 'name2' THEN 'whatever'                 ELSE ''            END ; 
like image 130
bobwienholt Avatar answered Sep 23 '22 02:09

bobwienholt


I don't know of any clean way to do what you're asking. An equivalent valid SQL update would be:

UPDATE tablename SET     col1 = CASE name WHEN 'name1' THEN 5 WHEN 'name2' THEN 3 ELSE 0 END,     col2 = CASE name WHEN 'name1' THEN '' WHEN 'name2' THEN 'whatever' ELSE '' END; 

Of course this isn't pretty and requires repeating the same cases (e.g. 'name1') multiple times, but I just don't think it's possible any other way.

like image 40
ean5533 Avatar answered Sep 22 '22 02:09

ean5533