The current date and time can be used to automatically initialize and update the TIMESTAMP and DATETIME columns (that is, the current timestamp).
You can set the current timestamp as the default value, the auto-update value, or both for any TIMESTAMP or DATETIME column in a table.
Use the DEFAULT CURRENT TIMESTAMP and ON UPDATE CURRENT TIMESTAMP clauses in column definitions to provide automatic properties. It doesn’t matter what order the clauses are in. Either can come first if both are present in a column definition. The definition of CURRENT TIMESTAMP is the same for all of its aliases. These are CURRENT_TIMESTAMP(), NOW(), LOCALTIME, LOCALTIME(), LOCALTIMESTAMP, and LOCALTIMESTAMP().
Either you can define the clause while creating the table or through ALTER statement, as shown below.
Examples:
CREATE TABLE MyTestTable (
dtCreated TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
dtUpdated DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
Altering the existing table:
ALTER TABLE MyTestTable
CHANGE dtCreated
dtCreated DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;
The syntax of the above command is-
ALTER TABLE table_name
CHANGE COLUMN old_name new_name
column_definition
[ FIRST | AFTER column_name ]
Happy learning!!!