Array Cardinality CHECK Constraint
Constrain array columns with CHECK using cardinality, = ANY element tests, and array_position blocklists — no subqueries are allowed in CHECK.
Code
-- 数组列的形状与取值都可以用 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
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
Report a problem with this exampleOpens a pre-filled issue on GitHub.