MySQL – Set Column Value if Another Column’s New Value is Different

MySQL

I have a table that has a column mycolumn and a column that has a boolean flag mycolumn_is_new. I want to set the second one to true when an UPDATE query changes the value of the first one. The user can type the same data or new data.

I have come up with this query, but mycolumn_is_new is always set to false :

UPDATE mytable SET
    mycolumn = '1234',
    mycolumn_is_new = IF(mycolumn <> '1234', TRUE, FALSE)
WHERE id = 321

Is it possible check the new and old value in a single query?

Best Answer

All expressions in the SET section are evaluated in the order in which they are written. So mycolumn in the second expression is equal to the value set in the first expression. Simply switch expressions - mycolumn_is_new = first.

Is it possible check the new and old value in a single query?

Yes, using user-defined variable. Save old, assign new, use old from variable and new from field. The simplest task need those method - switch the values of two fields in one UPDATE.