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.
Code
-- 发票主键是两列复合;明细表用复合外键引用
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
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.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.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.Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.
FAQ
- Which tables does the SQL touch?
- `invoices`, `line_items_simple`, `line_items_full`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.