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.

SqlData Integrity

Code

snippet
-- 规则:一条任务要么指派给员工、要么进入候选池,不允许同时指派或都不指派
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

FAQ

Which tables appear in this script?
`assignments` — referenced directly, no join needed.