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.

SqlData Integrity

Code

snippet
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

FAQ

What relations does the SQL touch?
`shipments`.