检查数组列的约束以验证长度 > 0

Ale*_*ein 6 postgresql null constraint check-constraints

我正在使用 postgres 表验证规则并尝试CHECK为数组列设置约束。一个想法是只允许长度 > 0 的数组。

这是我想要实现它的方式:

create table words_table (
  id serial primary key, 
  words varchar(20)[] CHECK (array_length(words, 1) > 0)
);
Run Code Online (Sandbox Code Playgroud)

但看起来它不起作用。o_o

insert into words_table (words) values ('{}');
//INSERT 0 1
Run Code Online (Sandbox Code Playgroud)

如何实现这样的约束?

Erw*_*ter 8

你可能不知道的关键点,引用手册

应该注意,如果检查表达式的计算结果为true 或 null 值,则满足检查约束。

大胆强调我的。

使用像 a_horse 解释的cardinality()修复这种情况。

明确禁止空数组会做同样的,更便宜的:

CHECK (words <> '{}')
Run Code Online (Sandbox Code Playgroud)

两种解决方案仍然允许其words本身为 NULL。您可能想要添加NOT NULL约束。

无论哪种方式,请注意 NULL总是通过CHECK约束。禁止表达式为 NULL 的一般解决方案:

CHECK (<expression> IS TRUE)
Run Code Online (Sandbox Code Playgroud)


a_h*_*ame 6

array_length(words, 1)null如果指定的数组维度不存在,则返回。你应该使用cardinality()

create table words_table 
(
  id serial primary key, 
  words varchar(20)[] CHECK (cardinality(words) > 0)
);
Run Code Online (Sandbox Code Playgroud)
insert into words_table (words) values ('{}');
Run Code Online (Sandbox Code Playgroud)

结果是:

create table words_table 
(
  id serial primary key, 
  words varchar(20)[] CHECK (cardinality(words) > 0)
);
Run Code Online (Sandbox Code Playgroud)