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

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-04 19:10:41339browse

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

Creating Timestamp Column with Default Value 'now'

In this scenario, the aim is to create a table with a timestamp column that automatically defaults to the current datetime upon insertion. Previously, attempts to define such a column using DATETIME('now') resulted in errors.

Solution: Using CURRENT_TIMESTAMP

Currently, SQLite version 3.1.0 and above provides a solution to this issue by employing CURRENT_TIMESTAMP within the DEFAULT clause. Here's how it's done:

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

This modification addresses the previous issue, allowing the creation of a timestamp column that seamlessly updates to the current datetime whenever a new row is inserted into the table. Its default value ensures automatic timestamp generation without the need for explicit assignments.

The above is the detailed content of How to Create a Timestamp Column with a Default Value of 'Now' 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