如何声明数组的元素不可为空?
How to declare the elements of an array non-nullable?
下面简单table
CREATE TABLE foo (
things VARCHAR ARRAY
);
可以插入 null
作为 things
的元素:
INSERT INTO foo VALUES ('{"hi", null, "ho"}');
但我不想让这个。
但是,将定义更改为以下内容,
CREATE TABLE foo (
things VARCHAR ARRAY NOT NULL
);
只防止这个
INSERT INTO foo VALUES (null);
这不是我想要的。 (我仍然想允许这样做。)
那么我如何声明数组列的元素不可为空?
您可以将 check
与 array_position()
一起使用,如下所示
CREATE TABLE foo (
things text[] NOT NULL check (array_position(things, null) is null)
);
你也可以检查空数组
CREATE TABLE foo (
things text[] NOT NULL check (things <> '{}' and array_position(things, null) is null)
);
您可以使用检查约束:
CREATE TABLE foo
(
things text[],
constraint check_things_not_null
check ( cardinality(things) = cardinality(array_remove(things, null)))
);
或者您可以使用 array_position()
CREATE TABLE foo
(
things text[],
constraint check_things_not_null
check ( array_position(things, null) is null)
);
下面简单table
CREATE TABLE foo (
things VARCHAR ARRAY
);
可以插入 null
作为 things
的元素:
INSERT INTO foo VALUES ('{"hi", null, "ho"}');
但我不想让这个。
但是,将定义更改为以下内容,
CREATE TABLE foo (
things VARCHAR ARRAY NOT NULL
);
只防止这个
INSERT INTO foo VALUES (null);
这不是我想要的。 (我仍然想允许这样做。)
那么我如何声明数组列的元素不可为空?
您可以将 check
与 array_position()
一起使用,如下所示
CREATE TABLE foo (
things text[] NOT NULL check (array_position(things, null) is null)
);
你也可以检查空数组
CREATE TABLE foo (
things text[] NOT NULL check (things <> '{}' and array_position(things, null) is null)
);
您可以使用检查约束:
CREATE TABLE foo
(
things text[],
constraint check_things_not_null
check ( cardinality(things) = cardinality(array_remove(things, null)))
);
或者您可以使用 array_position()
CREATE TABLE foo
(
things text[],
constraint check_things_not_null
check ( array_position(things, null) is null)
);