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.
Code
-- 条件必填: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
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.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.
FAQ
- Which tables appear in this script?
- `tickets`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.