When you find yourself needing to update a record column only if the column is currently NULL (where you don't want to overwrite actual data), you might be tempted to use the three-steps below:

  1. SELECT thecolumn FROM thetable WHERE id = xxx
  2. If thecolumn is empty, then
  3. UPDATE thetable SET thecolumn = 'value'

This not only requires two trips to your database, but also adds unneeded logic and lines of code to your script.

The update statement below takes care of the three steps above by including a conditional:

UPDATE table
SET thecolumn = IF(thecolumn IS NULL, 'value', thecolumn)
WHERE id = xxx

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *