Composite Foreign Key MATCH FULL

Compare composite foreign keys with MATCH SIMPLE and MATCH FULL: only the full variant rejects rows that reference a parent with half-null keys.

SqlData Integrity

Code

snippet
-- 发票主键是两列复合;明细表用复合外键引用
CREATE TABLE invoices (
    year     int,
    number   int,
    customer text NOT NULL,
    PRIMARY KEY (year, number)
);

-- MATCH SIMPLE(默认):引用列只要有 NULL,整组校验被跳过
CREATE TABLE line_items_simple (
    invoice_year   int,
    invoice_number int,
    amount         numeric NOT NULL,
    FOREIGN KEY (invoice_year, invoice_number)
        REFERENCES invoices (year, number)
);

-- MATCH FULL:要求引用列全 NULL 或全非 NULL,杜绝“半个引用”
CREATE TABLE line_items_full (
    invoice_year   int,
    invoice_number int,
    amount         numeric NOT NULL,
    FOREIGN KEY (invoice_year, invoice_number)
        REFERENCES invoices (year, number) MATCH FULL
);

INSERT INTO invoices VALUES (2026, 1001, 'Acme');

-- MATCH SIMPLE 接受这种只有年份、没有票号的半悬挂行
INSERT INTO line_items_simple VALUES (2026, NULL, 25.00);

-- MATCH FULL 拒绝同样的行:
-- ERROR: insert or update on table "line_items_full"
--        violates foreign key constraint
INSERT INTO line_items_full VALUES (2026, NULL, 25.00);

What the code does

Several statements share this file — INSERT / CREATE, with invoices, line_items_simple and line_items_full among the objects involved.

Breaking the statements into their working parts: NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; a foreign-key REFERENCES guard anchoring child rows to the parent table.

Applying it

Run the statement against the invoices table.

Statements that matter

CREATE TABLE line_items_full (
invoice_year   int,
invoice_number int,
amount         numeric NOT NULL,
FOREIGN KEY (invoice_year, invoice_number)
REFERENCES invoices (year, number) MATCH FULL
);
CREATE TABLE line_items_simple (
invoice_year   int,
invoice_number int,
amount         numeric NOT NULL,
FOREIGN KEY (invoice_year, invoice_number)
REFERENCES invoices (year, number)
);
CREATE TABLE invoices (
year     int,
number   int,
customer text NOT NULL,
PRIMARY KEY (year, number)
);

Interactive Tools for This Topic

FAQ

Which tables does the SQL touch?
`invoices`, `line_items_simple`, `line_items_full`.