Home >Database >Mysql Tutorial >How to Create a Timestamp Column with a Default 'Now' Value in SQLite?

How to Create a Timestamp Column with a Default 'Now' Value in SQLite?

Barbara Streisand
Barbara StreisandOriginal
2025-01-05 14:07:44440browse

How to Create a Timestamp Column with a Default 'Now' Value in SQLite?

Creating Timestamp Columns with Default 'now' Value

Creating a table with a timestamp column that automatically populates with the current date and time can be achieved using SQLite's DEFAULT clause.

The Dilemma:

As described in the problem, attempting to create a table with a timestamp column with a default value of DATETIME('now') results in an error.

Solution: Using CURRENT_TIMESTAMP

As suggested in the answer, SQLite version 3.1.0 and later offer the CURRENT_TIMESTAMP keyword, which can be used as a default value for timestamp columns. This keyword represents the current UTC date and time.

The corrected SQL statement to create the desired table would be:

CREATE TABLE test (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    t TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

This syntax ensures that every new row inserted into the test table will have the t column populated with the current timestamp, automatically and without the need for further updates or calculations.

The above is the detailed content of How to Create a Timestamp Column with a Default 'Now' Value in SQLite?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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