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

How to Set Default Values for DATETIME Columns in MySQL?

Barbara Streisand
Release: 2024-12-17 20:55:15
Original
486 people have browsed it

How to Set Default Values for DATETIME Columns in MySQL?

Setting Default Values for Datetime Columns in MySQL

In MySQL, setting a default value for a Datetime column differs from SQL Server's getdate() function.

MySQL versions prior to 5.6.5 do not allow default values for DATETIME fields. However, you can use TIMESTAMP instead:

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

Inserting a row without specifying a timestamp will automatically populate it with the current time:

INSERT INTO test (str) VALUES ('demo');
Copy after login

Caution: Using CURRENT_TIMESTAMP as a default can lead to unexpected behavior during updates. To maintain the original timestamp, you must explicitly set the column to its current value:

UPDATE test SET ts = ts;
Copy after login

MySQL 5.6.5 and Later

MySQL 5.6.5 introduces support for default values for DATETIME fields:

CREATE TABLE test2 (
  str VARCHAR(32),
  dt DATETIME DEFAULT '2000-01-01 00:00:00'
);
Copy after login

This method is preferred over using TIMESTAMP for setting default values for datetime columns.

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