CHECK num_nonnulls Exactly One Target
Enforce exactly-one-of-two columns with a CHECK constraint over num_nonnulls, rejecting rows that assign both or neither target.
Code
-- 规则:一条任务要么指派给员工、要么进入候选池,不允许同时指派或都不指派
CREATE TABLE assignments (
id bigserial PRIMARY KEY,
title text NOT NULL,
employee_id bigint,
candidate_id bigint,
-- num_nonnulls 数出参数里非 NULL 的个数:= 1 才合法
CONSTRAINT assignment_exactly_one_target
CHECK (num_nonnulls(employee_id, candidate_id) = 1)
);
INSERT INTO assignments (title, employee_id) VALUES ('rotate keys', 42); -- 通过
INSERT INTO assignments (title, candidate_id) VALUES ('triage p1', 7); -- 通过
-- 两个都为空:0 个目标,违反约束被当场拒绝
INSERT INTO assignments (title) VALUES ('nothing assigned');
-- 两个都有值:2 个目标,同样违反
INSERT INTO assignments (title, employee_id, candidate_id) VALUES ('both', 42, 7);How it works
Several statements share this file — INSERT / CREATE, with assignments among the objects involved.
Mechanically, the statements are built from: 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.
Using it
The assignments table is the working surface here.
Key statements
INSERT INTO assignments (title, employee_id) VALUES ('rotate keys', 42); -- 通过
INSERT INTO assignments (title, candidate_id) VALUES ('triage p1', 7); -- 通过
INSERT INTO assignments (title) VALUES ('nothing assigned');
CREATE TABLE assignments (
id bigserial PRIMARY KEY,
title text NOT NULL,
employee_id bigint,
candidate_id bigint,
CONSTRAINT assignment_exactly_one_target
CHECK (num_nonnulls(employee_id, candidate_id) = 1)
);
INSERT INTO assignments (title, employee_id, candidate_id) VALUES ('both', 42, 7);
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
- Which tables appear in this script?
- `assignments` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.