SQLite 插入记录时,怎样用 DEFAULT CURRENT_TIMESTAMP 自动填写创建时间?

April 22, 2025

新建账号时,调用方知道用户名,数据库知道记录是什么时候写进去的。要把创建时间交给 SQLite,可以给这一列声明 DEFAULT CURRENT_TIMESTAMP,然后在 INSERT 的列清单里省略它。只写 TIMESTAMP NOT NULL 会要求这列有值;如果既没有默认值,插入时又没传,SQLite 就会报非空约束错误。1

省略时间列,SQLite 会存下什么?

在空数据库里试一个只有两列的例子。插入账号时只传用户名,读回来时同时看时间和它的存储类型。

CREATE TABLE users (
    user_name         TEXT NOT NULL UNIQUE,
    user_created_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

INSERT INTO users (user_name) VALUES ('lin');

SELECT user_created_time, typeof(user_created_time)
FROM users
WHERE user_name = 'lin';

第一列是插入时的 UTC 时间,格式为 YYYY-MM-DD HH:MM:SS,精确到秒。第二列是 text。SQLite 没有专用的日期时间存储类型,这个默认值写入的是文本。以后即便用 UPDATE 改了用户名,创建时间也会保留。12

显式传入 NULL 也会用默认值吗?

不会。我当时看过的 Stack Overflow 回答特意提醒:“However, if your INSERT command explicitly sets this field to NULL, it will be set to NULL.”3 那个回答里的时间列允许为空。如果沿用上面的 NOT NULL 表结构,下面这句会得到 NOT NULL constraint failed: users.user_created_time。

INSERT INTO users (user_name, user_created_time)
VALUES ('chen', NULL);

这关系到应用里怎样拼插入语句。如果语句写了两个占位符,再把缺失的创建时间绑定成 NULL,SQLite 收到的是一个明确的空值。希望数据库填时间,就只列出 user_name。反过来,导入已有账号时,如果要保留原始创建时间,可以显式传入那个时间。

我什么时候把默认值用到了用户表里?

2025 年 4 月 22 日下午,我在写资产管理系统的用户表。那天我从自动时间戳的问答读到 SQLite 的日期函数文档。当天提交的第一版用户表里,创建时间仍然只写了 user_created_time TIMESTAMP NOT NULL。4

4 月 24 日加登录功能时,我要在初始化数据库时创建默认管理员。这一版把字段改成了 TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP。插入管理员的语句列出了登录名、昵称、邮箱等字段,省去了创建时间,正好把这个值交给数据库填写。5 同一张表里的登录名为什么单独加了唯一约束,见SQLite 的 PRIMARY KEY 和 UNIQUE 都能加快查询吗?。

Footnotes

  1. SQLite. (n.d.). CREATE TABLE, §3.2 “The DEFAULT clause”. SQLite Documentation. 省略列时的取值与 UTC 格式 ↩ ↩2

  2. SQLite. (n.d.). Date and time functions, §1 “Overview”. SQLite Documentation. SQLite 中日期与时间的存储形式 ↩

  3. CL. (2013, January 22). How to have an automatic timestamp in SQLite? [Answer, paragraph following the CREATE TABLE example]. Stack Overflow. 默认值与显式 NULL ↩

  4. borui. (2025, April 22). Fix actions endpoint error handling; add user table creation [Commit dfc8bd4]. GitHub. 第一版 users 表 ↩

  5. borui. (2025, April 24). Add login feature; add router using wouter [Commit b94e7c7]. GitHub. 默认时间与管理员的 INSERT ↩

© 2025 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2025-04-22). SQLite 插入记录时,怎样用 DEFAULT CURRENT_TIMESTAMP 自动填写创建时间?. https://caiborui.com/blog/2025-04-22-zh-sqlite-default-current-timestamp

@misc{borui2025-0d6fd9fa,
  author = {borui},
  title = {{SQLite 插入记录时,怎样用 DEFAULT CURRENT_TIMESTAMP 自动填写创建时间?}},
  year = {2025},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2025-04-22-zh-sqlite-default-current-timestamp}
}