Home  >  Article  >  Database  >  How Do You Auto-Populate Creation Timestamps in MySQL Records?

How Do You Auto-Populate Creation Timestamps in MySQL Records?

Barbara Streisand
Barbara StreisandOriginal
2024-10-26 09:08:30734browse

How Do You Auto-Populate Creation Timestamps in MySQL Records?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn