CHECK Constraint Conditional Required Field

Make a column conditionally required with a CHECK: status = 'closed' must carry closed_at, while other statuses leave it free; NOT NULL cannot express this.

SqlData Integrity

Code

snippet
-- 条件必填:status = 'closed' 时 closed_at 必须有值,其余状态不要求
CREATE TABLE tickets (
    ticket_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    status    text NOT NULL DEFAULT 'open',
    closed_at timestamptz,
    CONSTRAINT closed_requires_timestamp
        CHECK (status <> 'closed' OR closed_at IS NOT NULL)
);

INSERT INTO tickets (status, closed_at) VALUES ('open', NULL);     -- 通过
INSERT INTO tickets (status, closed_at) VALUES ('closed', now());  -- 通过

-- INSERT INTO tickets (status, closed_at) VALUES ('closed', NULL);
--  ↑ 违反 closed_requires_timestamp:关闭却没给时间,写入被拒绝

-- 约束只看当前行:已有行回填 closed_at 即可满足
UPDATE tickets SET closed_at = now() WHERE status = 'closed' AND closed_at IS NULL;

How the snippet works

What runs here is INSERT / UPDATE / CREATE — tickets are the objects involved.

Mechanically, the statements are built from: a WHERE clause narrowing which rows one statement affects; 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; DEFAULT values filling omitted columns; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.

Applying it

The tickets table is the working surface here.

Statements that matter

INSERT INTO tickets (status, closed_at) VALUES ('open', NULL);     -- 通过
INSERT INTO tickets (status, closed_at) VALUES ('closed', now());  -- 通过
UPDATE tickets SET closed_at = now() WHERE status = 'closed' AND closed_at IS NULL;
CREATE TABLE tickets (
ticket_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
status    text NOT NULL DEFAULT 'open',
closed_at timestamptz,
CONSTRAINT closed_requires_timestamp
CHECK (status <> 'closed' OR closed_at IS NOT NULL)
);

Interactive Tools for This Topic

FAQ

Which tables appear in this script?
`tickets`.