Home  >  Article  >  Database  >  How to Automate Record Creation Timestamp Storage in MySQL?

How to Automate Record Creation Timestamp Storage in MySQL?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-26 18:12:02498browse

How to Automate Record Creation Timestamp Storage in MySQL?

Automate Record Creation Timestamp Storage in MySQL

MySQL offers the possibility of automatically recording the creation timestamp of new records, eliminating the need for manual entry. To achieve this, consider utilizing the DEFAULT constraint with the CURRENT_TIMESTAMP value.

Solution:

Utilize the DEFAULT constraint to initialize the column with the current timestamp:

CREATE TABLE ...
  your_timestamp_column TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  ...

For an existing table, modify the column definition using the ALTER TABLE statement:

ALTER TABLE your_table
ALTER COLUMN timestamp_column SET DEFAULT CURRENT_TIMESTAMP

By default, the column will be populated with the current date and time when an INSERT statement is executed, unless explicitly specified otherwise. Alternatively, you can specify NULL or the DEFAULT value to take advantage of the default constraint, assuming the column allows NULL values.

The above is the detailed content of How to Automate Record Creation Timestamp Storage in MySQL?. 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