Creating Timestamp Columns with Default 'now' Value
Creating a table with a timestamp column that automatically defaults to the current date and time can be done using the CURRENT_TIMESTAMP keyword. The DEFAULT clause in SQL allows you to specify a default value for a column when a value is not explicitly provided during data insertion.
To create a table with a timestamp column that defaults to 'now', you can use the following syntax:
CREATE TABLE table_name ( column_name TIMESTAMP DEFAULT CURRENT_TIMESTAMP );
For example:
CREATE TABLE test ( id INTEGER PRIMARY KEY AUTOINCREMENT, t TIMESTAMP DEFAULT CURRENT_TIMESTAMP );
Prior to version 3.1.0, using DATETIME('now') as the default value for a timestamp column would result in an error. However, with the introduction of CURRENT_TIMESTAMP, the default value can be set to the current UTC date and time.
The CURRENT_TIMESTAMP keyword returns a text representation of the current UTC date and time in the format "YYYY-MM-DD HH:MM:SS". This ensures that the timestamps stored in the database are consistent and up-to-date, making it easier to track temporal data and monitor changes over time.
The above is the detailed content of How to Set a Timestamp Column's Default Value to 'Now' in SQL?. For more information, please follow other related articles on the PHP Chinese website!