Home > Database > Mysql Tutorial > How to Set Default Values for MySQL Datetime Columns?

How to Set Default Values for MySQL Datetime Columns?

Mary-Kate Olsen
Release: 2025-01-04 05:14:39
Original
562 people have browsed it

How to Set Default Values for MySQL Datetime Columns?

Setting Default Values for MySQL Datetime Columns

In SQL Server, the getdate() function is used to define a default value for a Datetime column. But in MySQL, the situation is different.

Prior to MySQL 5.6.5, it was not possible to set a default value for a Datetime column. However, you could achieve this functionality using a Timestamp column instead. In MySQL 5.x, the following syntax can be used:

CREATE TABLE test (
  str VARCHAR(32),
  ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Copy after login

This syntax ensures that the ts column will have a default value of the current timestamp upon record insertion.

Important Note:

In MySQL versions prior to 5.6.5, using CURRENT_TIMESTAMP as the default value for a Datetime column was not allowed. It is important to note that the default value will automatically reset to the current timestamp during record updates if you specify a column with CURRENT_TIMESTAMP ON as the default. This means that you must always include [your column name] = [your column name] (or another value) in your UPDATE statement to prevent the value from resetting to the current timestamp.

The above is the detailed content of How to Set Default Values for MySQL Datetime Columns?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template