Skip to content

NOT NULL Constraint Violation

错误信息

                空值 in 列 violates 不-空 constraint
              

快速摘要

你 attempted 到 insert or 更新行 不使用 providing 值 for 列 marked NOT NULL.

为什么发生

  • Omitting 必需列 从 INSERT 语句

  • Passing 空/undefined 从 application for 必需字段

  • 列是 更改到 NOT NULL 但 existing 行有 NULL 值

最小示例

✗ 错误代码
INSERT INTO users (id) VALUES (1);
-- But 'email' is NOT NULL and was not provided
✓ 修复代码
INSERT INTO users (id, email) VALUES (1, '[email protected]');

email 列是 NOT NULL, 所以它 必须是 provided. 添加它 到 INSERT fixes 错误.

如何诊断

  • 读取错误到 identify 哪个列 需要值

  • 检查你的 INSERT or UPDATE 语句 — 是列 provided?

  • 验证 application 是不 发送空 for 必需字段

如何修复

  • Provide 值 for NOT NULL 列

  • 添加 DEFAULT 值到 列如果 appropriate

  • 移除 NOT NULL constraint 如果列 应该允许 NULL

  • 更新 existing NULL 值之前添加 NOT NULL constraint

如何预防

  • 验证必需字段 in 你的 application 之前 inserting

  • Use 表单 validation 到 ensure 用户 fill in 必需字段

  • Document 哪个列 是必需

相关资源

相关术语

相关课程

← 返回语言