PostgreSQL:为什么NOT NULL不在这里工作?

时间:2014-04-29 00:43:31

标签: sql postgresql psql postgresql-9.3

我正在用PostgreSQL开发我的第一个应用程序。

场景

这就是我的桌子" person"看起来像是:

   Column   |            Type             |                      Modifiers
------------+-----------------------------+-----------------------------------------------------
 id         | bigint                      | not null default nextval('person_id_seq'::regclass)
 first_name | character varying(255)      | not null
 last_name  | character varying(255)      | not null
 email      | character varying(255)      | not null
 password   | character varying(255)      | not null
 created_at | timestamp without time zone |
 updated_at | timestamp without time zone |
Indexes:
    "person_pkey" PRIMARY KEY, btree (id)
    "person_email_unique" UNIQUE CONSTRAINT, btree (email)
    "person_id_unique" UNIQUE CONSTRAINT, btree (id)
Referenced by:
    TABLE "access" CONSTRAINT "access_person_id_foreign" FOREIGN KEY (person_id) REFERENCES person(id)

这是使用knex.schema中的迁移创建的。

如果我在psql中运行以下查询...

insert into person (first_name, last_name, email, password) values ('Max', 'Mustermann', '', '123123123');

我回来INSERT 0 1并成功插入了行:

id | first_name | last_name  |               email               |    password    |       created_at        |       updated_at
----+------------+------------+-----------------------------------+----------------+-------------------------+-------------------------
12 | Max        | Mustermann |                                   | 123123123      |                         |

我的问题:

我希望操作失败,因为没有指定电子邮件(NOT NULL)。为什么不失败?

非常感谢你的帮助!

最高

3 个答案:

答案 0 :(得分:4)

某些DBMS(如Oracle)将空字符串('')视为NULL。其他(如MySQL,PostgreSQL等)将空字符串和NULL视为不同。

PostgreSQL将''视为空字符串,而不是NULL,因此您的insert语句已成功执行。

答案 1 :(得分:2)

null和一个空字符串不是相同的值,通过传入一个满足要求的空字符串。

如果您查询

insert into person (first_name, last_name, password) 
values ('Max', 'Mustermann', '123123123');

然后会抛出错误,因为您没有传递电子邮件的值

答案 2 :(得分:1)

因为您没有传递空值。你传了一个空字符串。