Default Timestamp Mysql

Asked

Viewed 5,224 times

2

How do I put the field value by default timestamp current?

Precise alterar my table to add a field timestamp not null that has by default the current, with this I need all previous registrations to have the current timestamp as well.

1 answer

4


When creating the field, set it like this:

dataHora TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP;

If you are going to modify the structure of an existing table, use this query before of the modification:

UPDATE minhaTabela SET dataHora = CURRENT_TIMESTAMP WHERE dataHora IS NULL;

Follows the query to modify the field:

ALTER TABLE
   minhaTabela
CHANGE
   dataHora
   dataHora TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP;


Notes:

  • Remember you can use DATETIME also to store dates that do not change.

  • If the field is defined in this way:

    dataHora TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    

    your field will be changed in UPDATES also. If not the desired effect, just use the ALTER TABLE above without defining the ON UPDATE.

  • To check the table structure use:

    SHOW CREATE TABLE minhaTabela;
    

    for the EXPLAIN does not show settings ON UPDATE.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.