7

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?

1
  • 1
    You don't need the second case. Set A = A does nothing. Filter this in the where clause, should be faster: WHERE A IS NOT NULL AND (A > 20 OR A <= 1)
    – Ortiga
    Mar 15, 2012 at 15:43

3 Answers 3

12

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 <=.

0
5
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;
3
  • 1
    Shouldn't the cases omit the single quotes to use int values (rather than a string literals like '20' and 'A' etc.)?
    – JYelton
    Mar 15, 2012 at 15:43
  • its illustrative, his original has similar type mismatches i didnt want to guess Mar 15, 2012 at 15:43
  • Good point. Though if the stored value is an int, comparing it to '20' will work in mysql, likewise setting it to '20' will also work, as mysql will evaluate and convert string <-> int. However 'A' will result in a type error.
    – JYelton
    Mar 15, 2012 at 15:47
0

With the help of below mentioned query you can update salary field based on conditions. It's a single line update query to update multiple rows in a table based on conditions.

UPDATE table
SET salary = Case
WHEN designation='developer' THEN salary + salary*0.20
WHEN designation='manager' THEN salary + salary*0.30
END

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.