I'm developing my first ever application with PostgreSQL.

The Scenario

This is what my table "person" looks like:

   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)

This was created using migrations in knex.schema.

If I run the following query in psql...

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

I get back INSERT 0 1 and the row is successfully inserted:

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

My Question:

I expect the operation to fail, because no e-mail (NOT NULL) was specified. Why does it not fail?

Thank you very much for your help!

Max

有帮助吗?

解决方案

Some DBMS (like Oracle) treats empty string ('') as NULL. Others (like MySQL, PostgreSQL, etc) treat empty string and NULL as different.

PostgreSQL treats '' as empty string, not NULL, so your insert statement executed successfully.

其他提示

null and an empty string are not the same values, by passing in an empty string you have satisfied the requirement.

If you query was

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

then an error would be thrown because you are not passing in a value for email

Because you didn't pass a null value. You passed an empty string.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top