首页 > 解决方案 > 如何声明数组的元素不可为空?

问题描述

在下面的简单表格中

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);

这不是我想要的。(我仍然想允许这样做。)

那么我怎样才能声明不是列,而是数组列的元素不可为空呢?

标签: sqlarrayspostgresqldatabase-designsql-null

解决方案


您可以使用checkwitharray_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)
);

推荐阅读