I want to update a table in MySQL like this:
UPDATE Table
SET A = '20' IF A > 20
SET A = A IF A < 20
SET A = 0 IF A <= 1
WHERE A IS NOT NULL;
But the above SQL is not valid Syntax. I also tried this:
UPDATE table
SET A = IF(A > 20, 20, IF(A < 20, A, 0));
But is also invalid Syntax. How do I use an if statement in an update query like this?
MySQL IF ELSE. IF() function can be used independently with MySQL queries directly, however, MySQL IF ELSE is used as a statement as part of the stored procedures or functions.
IF color = red THEN dbms_output. put_line('You have chosen a red car') ELSE dbms_output. put_line('Please choose a color for your car'); END IF; If the Boolean expression condition evaluates to true, then the if-then block of code will be executed otherwise the else block of code will be executed.
To do a conditional update depending on whether the current value of a column matches the condition, you can add a WHERE clause which specifies this. The database will first find rows which match the WHERE clause and then only perform updates on those rows.
UPDATE Syntax Notice the WHERE clause in the UPDATE statement. The WHERE clause specifies which record(s) that should be updated. If you omit the WHERE clause, all records in the table will be updated!
I think you were 99% there:
UPDATE table
SET A = IF(A > 20, 20, IF(A < 20 && A > 1, A, 0))
WHERE A IS NOT NULL;
Add the && A > 1
to the second IF statement and your third condition is satisfied.
Edit:
Per @Andre's comment to the question and the suggestion that the nested IF
is difficult to read, you could also do this as a couple of queries that don't do any unnecessary work and are readable:
UPDATE table SET A = 20 WHERE A > 20;
UPDATE table SET A = 0 WHERE A <= 1;
When A is NULL, it will not meet either of these conditions, and thus eliminates the need to specify that A not be NULL.
Next, there's no need for the third condition as @Andre suggested. If A is between 1 and 20, it gets left as-is.
Finally, setting A to 0 where A is less than or equal to 1 seems unusual. Values of 1 will be changed to 0. If you intend to simply set values less than 1 (including negative values) to 0, then you should swap <
for <=
.
UPDATE Table
SET A = Case
When A > 20 Then 20
When A <= 1 Then 0
End
WHERE A IS NOT NULL and ( A > 20 or A <= 1 )
or more simply, 2 statements
UPDATE Table
SET A = 20
where A > 20;
UPDATE Table
SET A = 0
where A <= 1;
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