Joseph Erickson Joseph Erickson - 4 months ago 34
MySQL Question

Evaluating truthy values

I wanted to say something like:

if field_1 then set field_2 = 1


Meaning, if field_1 holds a truthy value, do something else. Can an IF statement in sql execute this kind of evaluation?

Answer

Use CASE WHEN THEN and set field2 to 1 if the CASE WHEN is true, else use ELSE to set field2 to what it was before.

UPDATE table 
SET field2 = CASE
WHEN field1 IS NOT NULL 
THEN 1
ELSE field2
END;