Search code examples
mysqlsqldatabasesql-updatedefault

How to reset fields to DEFAULT value in a MYSQL table when update a record with some value?


i've a MYSQL table called "customers" with the following fields:

  • id (primary key, int, autoincrement)
  • name (varchar(20), default value='')
  • surname (varchar(20), default value='')
  • age (int, default value=NULL)
  • city (varchar(20), default value='')

The question is simple:

If i had to update "name" and "surname" i would like all the other fields of that record to be returned to their starting values without expressly declaring them.

Is there any instruction that automatically does this?

Thank you all! :)


Solution

  • Is there any instruction that automatically does this?

    No. MySQL supports ON UPDATE clauses in columns definitions for datetime and timestamp only (and only to set the column to the current date). Other databases do not even support ON UPDATE

    So you will need to explicitly assign the columns you want to reset in your update statement. You can simplify the logic a little by using DEFAULT as a target value, so you don’t need to remember each and every default value.

    update customers 
    set
        name = 'foo',
        surname = 'bar',
        age = default,
        city = default
    where id = 1
    

    Unrelated note: it is not a good practice to store an age, since this information changes over time. Instead you can store the date of birth, and compute the age on the fly when needed (or use a view).