SET DEFAULT FK Fails Without Parent
ON DELETE SET DEFAULT rewrites child keys to the column default, and the delete fails outright when that default does not satisfy the foreign key.
Code
-- ON DELETE SET DEFAULT:父行被删时子表外键改写成列默认值
-- 文档明确:默认值不满足外键约束(父表里没有它)时操作直接 fail
CREATE TEMP TABLE accounts (
account_id int PRIMARY KEY
);
CREATE TEMP TABLE invoices (
invoice_id int PRIMARY KEY,
account_id int NOT NULL DEFAULT 999
REFERENCES accounts (account_id) ON DELETE SET DEFAULT
);
INSERT INTO accounts VALUES (1), (2);
INSERT INTO invoices VALUES (100, 1), (101, 2);
-- 默认值 999 不在 accounts(parent 表)里:删除父行会连带失败,语句回滚
DELETE FROM accounts WHERE account_id = 1;
-- ERROR: 外键约束违反(violates foreign key constraint),invoice 100 仍指向 1
SELECT invoice_id, account_id FROM invoices ORDER BY invoice_id;
-- 默认值在父表里真实存在时:SET DEFAULT 正常生效
INSERT INTO accounts VALUES (999) ON CONFLICT DO NOTHING;
DELETE FROM accounts WHERE account_id = 2;
SELECT invoice_id, account_id FROM invoices ORDER BY invoice_id;
-- invoice 101 改挂 999;invoice 100 因为第一次 DELETE 失败仍指向 1
DROP TABLE invoices;
DROP TABLE accounts;Inside the snippet
Several statements share this file — SELECT / INSERT / DELETE / CREATE, with accounts and invoices among the objects involved.
accounts and invoices are created in this same file as session-local temp tables — nothing needs to exist beforehand, and they go away at session end.
Breaking the statements into their working parts: a WHERE clause restricting which rows the statement reaches; an ORDER BY that fixes the output order; an upsert guard (ON CONFLICT/MERGE) that turns insert-or-update into one atomic statement; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; DEFAULT values filling omitted columns; a foreign-key REFERENCES guard that pins each row to the parent table.
Using it
The file is self-contained: it creates the session-local tables it uses (accounts, invoices), so run it as a whole against a scratch database.
Key statements
CREATE TEMP TABLE invoices (
invoice_id int PRIMARY KEY,
account_id int NOT NULL DEFAULT 999
REFERENCES accounts (account_id) ON DELETE SET DEFAULT
);
SELECT invoice_id, account_id FROM invoices ORDER BY invoice_id;
CREATE TEMP TABLE accounts (
account_id int PRIMARY KEY
);
Interactive Tools for This Topic
FAQ
- Name the tables involved in this file.
- `accounts`, `invoices`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.