Auto-Populating Creation Timestamps in MySQL Records
MySQL provides a convenient feature to automatically store the timestamp of record creation. Unlike the timestamp data type, which updates upon every record update, this technique preserves the initial creation date.
To implement this, you can leverage the DEFAULT constraint by setting the default value to the current timestamp. Here's how to do it:
Creating a Table:
CREATE TABLE your_table ( id INT PRIMARY KEY, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP );
Modifying an Existing Table:
ALTER TABLE your_table ALTER COLUMN created_at SET DEFAULT CURRENT_TIMESTAMP;
When you insert a new record without specifying a value for created_at, MySQL automatically populates it with the current timestamp. NULL or DEFAULT values also trigger the use of the default constraint.
This ensures that the creation timestamp is captured accurately and remains unchanged throughout the record's existence.
The above is the detailed content of How Do You Auto-Populate Creation Timestamps in MySQL Records?. For more information, please follow other related articles on the PHP Chinese website!