CHECK Constraint NULL Pass Through
A CHECK expression passes whenever it evaluates to NULL, so constraints that look strict still allow missing values unless the predicate is written NULL-aware.
Code
CREATE TABLE shipments (
shipment_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
carrier text,
tracking_code text,
-- 看起来"tracking_code 必须够长",其实 tracking_code 为 NULL 时
-- 表达式结果是 NULL,CHECK 对 NULL 放行:空值照样插入成功
CONSTRAINT tracking_min_length
CHECK (char_length(tracking_code) >= 8),
-- NULL 感知的写法:COALESCE 把 NULL 变成显式拒绝
CONSTRAINT tracking_required_or_absent_pair
CHECK ((carrier IS NULL) = (tracking_code IS NULL))
);
-- 通过:tracking_code 为 NULL,第一个 CHECK 的结果是 NULL → 放行
INSERT INTO shipments (carrier, tracking_code) VALUES (NULL, NULL);
-- 违反配对约束:一个非空一个空
-- INSERT INTO shipments (carrier, tracking_code) VALUES ('ups', NULL);
-- 违反长度检查:非空但太短,此时表达式结果是 false → 拒绝
-- INSERT INTO shipments (carrier, tracking_code) VALUES ('ups', 'short');What the code does
Several statements share this file — INSERT / CREATE, with shipments among the objects involved.
Breaking the statements into their working parts: a CHECK constraint that rejects out-of-domain values at write time; a PRIMARY KEY that enforces row identity; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.
Applying it
Run the statement against the shipments table.
Statements that matter
CREATE TABLE shipments (
shipment_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
carrier text,
tracking_code text,
CONSTRAINT tracking_min_length
CHECK (char_length(tracking_code) >= 8),
CONSTRAINT tracking_required_or_absent_pair
CHECK ((carrier IS NULL) = (tracking_code IS NULL))
);
INSERT INTO shipments (carrier, tracking_code) VALUES (NULL, 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.
FAQ
- What relations does the SQL touch?
- `shipments`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.