CREATE DOMAIN Reusable Check Constraints

Define a check constraint once with CREATE DOMAIN and reuse it across columns; NULL passes, but any invalid email insertion fails loudly.

SqlData Integrity

Code

snippet
-- 域类型:把一条 CHECK 约束定义一次,多表多列复用
CREATE DOMAIN email_address AS text
    CHECK (VALUE ~ '^[^@\s]+@[^@\s]+\.[^@\s]+$');

CREATE TABLE contacts (
    id     integer PRIMARY KEY,
    email  email_address NOT NULL,
    backup email_address          -- 可空列:NULL 不触发 CHECK,非空才校验
);

INSERT INTO contacts (id, email)
VALUES (1, '[email protected]');    -- 合法插入

-- 非法值被域 CHECK 整条拒绝,规则不需要在每个表里重复声明
-- INSERT INTO contacts (id, email) VALUES (2, 'not-an-email');

What the code does

Several statements share this file — INSERT / CREATE, with contacts among the objects involved.

What the statements actually assemble: 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.

Applying it

Run it in the contacts database context.

Statements that matter

CREATE TABLE contacts (
id     integer PRIMARY KEY,
email  email_address NOT NULL,
backup email_address          -- 可空列:NULL 不触发 CHECK,非空才校验
);
CREATE DOMAIN email_address AS text
CHECK (VALUE ~ '^[^@\s]+@[^@\s]+\.[^@\s]+$');

Interactive Tools for This Topic

FAQ

Which tables does this file reference?
`contacts`.