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?
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.
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.
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);
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.
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 ;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With