Home > Database > Mysql Tutorial > How to Set a Default Value for a MySQL Datetime Column?

How to Set a Default Value for a MySQL Datetime Column?

Linda Hamilton
Release: 2024-12-13 10:26:12
Original
993 people have browsed it

How to Set a Default Value for a MySQL Datetime Column?

Creating a Default Value for a MySQL Datetime Column

In MySQL, setting a default value for a Datetime column can be achieved using the TIMESTAMP data type. While SQL Server uses getdate() for this purpose, MySQL does not have an equivalent function for DATETIME fields.

However, you can utilize the TIMESTAMP data type to create a default value that automatically populates the field with the current timestamp upon row insertion. Here's how:

mysql> create table test (str varchar(32), ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP);
Query OK, 0 rows affected (0.00 sec)
Copy after login

In this example, the ts column in the test table is defined as a TIMESTAMP field and given a default value of CURRENT_TIMESTAMP. When a new row is inserted into the table without explicitly specifying a value for ts, the default value will be automatically populated with the current system time.

mysql> insert into test (str) values ("demo");
Query OK, 1 row affected (0.00 sec)
Copy after login
mysql> select * from test;
+------+---------------------+
| str  | ts                  |
+------+---------------------+
| demo | 2023-03-08 15:23:45 | 
+------+---------------------+
1 row in set (0.00 sec)
Copy after login

As you can see, the ts column in the test table has been automatically populated with the current timestamp when the new row was inserted.

Important Note:

For default values in DATETIME columns, MySQL 5.6.5 and later versions now support the CURRENT_TIMESTAMP function. However, in earlier versions, this feature is only available for TIMESTAMP columns.

The above is the detailed content of How to Set a Default Value for a MySQL Datetime Column?. 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