Home > Database > Mysql Tutorial > body text

How do I automatically store the timestamp of a record\'s creation in MySQL?

DDD
Release: 2024-10-26 15:55:31
Original
344 people have browsed it

How do I automatically store the timestamp of a record's creation in MySQL?

Automatic Record Creation Timestamping in MySQL

In MySQL, you may encounter a situation where you want to automatically store the timestamp of a record's creation upon insertion. To achieve this, you cannot rely on the timestamp data type with current_timestamp as the default value, as it will be updated every time the record is modified. Instead, there's a more specific solution available.

To automatically store the creation timestamp, you can use the DEFAULT constraint with CURRENT_TIMESTAMP. Here's how:

For a new table:

<code class="sql">CREATE TABLE your_table (
  ...
  your_date_column DATETIME DEFAULT CURRENT_TIMESTAMP
  ...
);</code>
Copy after login

For an existing table:

<code class="sql">ALTER TABLE your_table
ALTER COLUMN date_column SET DEFAULT CURRENT_TIMESTAMP;</code>
Copy after login

By applying this constraint, whenever a new record is inserted without explicitly specifying a value for the date_column, the current date and time at the moment of insertion will be automatically used. NULL and DEFAULT are both valid values to trigger the default constraint, assuming the column is nullable.

The above is the detailed content of How do I automatically store the timestamp of a record\'s creation in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!