Array Cardinality CHECK Constraint

Constrain array columns with CHECK using cardinality, = ANY element tests, and array_position blocklists — no subqueries are allowed in CHECK.

SqlData Integrity

Code

snippet
-- 数组列的形状与取值都可以用 CHECK 表达(CHECK 内不能写子查询)
CREATE TABLE articles (
    id    bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    title text NOT NULL,
    tags  text[] NOT NULL,
    -- 形状:至少 1 个、至多 5 个标签
    CHECK (cardinality(tags) BETWEEN 1 AND 5),
    -- 取值:不允许空串标签(= ANY 对数组逐元素比较)
    CHECK (NOT ''::text = ANY(tags)),
    -- 保留字:'internal' 是系统保留标签,禁止用户提交
    CHECK (array_position(tags, 'internal') IS NULL)
);

-- 违反任一条的 INSERT 或 UPDATE 都会被整行拒绝:
-- tags = '{}'                    → cardinality 下限违反
-- tags = ARRAY['go', '']         → 空串元素违反
-- tags = ARRAY['go', 'internal'] → 保留标签违反

What the code does

At its core this is a single CREATE statement.

Breaking the statements into their working parts: a CHECK constraint that rejects out-of-domain values at write time; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.

Statements that matter

CREATE TABLE articles (
id    bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL,
tags  text[] NOT NULL,
CHECK (cardinality(tags) BETWEEN 1 AND 5),
CHECK (NOT ''::text = ANY(tags)),
CHECK (array_position(tags, 'internal') IS NULL)
);

Interactive Tools for This Topic