SQL: update field value to itself

Sometimes your application contains query update code that you don’t wish to modify, or that you don’t have access to modify.

For example, using PHP:

UPDATE table SET field1 = " . $value1 . ", field2 = " . $value2 . " WHERE id = " . $id . ";

You may still have access to modify the values that get used in the query – in this case, $value1 and $value2.

Sometimes you don’t want to update a particular field with a new value – you’d like to keep it as it is. However, despite whether or not a value should be something new, the UPDATE query still runs, so you need some way of telling the query to leave a particular field value as is.

The easiest way to avoid updating a field is to simply exclude it from the query:

UPDATE table SET field2 = " . $value2 . " WHERE id = " . $id . ";

In this case, we removed the instructions to update field1. If we don’t tell it to update field1, it leaves the value as is.

But remember – we don’t want to modify the query instructions, or we may not have access to modify it. The instructions run regardless of fields that should or should not get updated.

For the field that needs to remain the same, you could set it’s value to itself. Our modified query would look like:

UPDATE table SET field1 = field1, field2 = " . $value2 . " WHERE id = " . $id . ";

Notice field1 is set to itself:

field1 = field1

No need to adjust the query instructions. The field value remains the same.

2 thoughts on “SQL: update field value to itself

Comments are closed.