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.
Code
-- 域类型:把一条 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
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.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.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.
FAQ
- Which tables does this file reference?
- `contacts`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.