ON UPDATE CASCADE Ripples Child Keys
Renaming a referenced natural key ripples into child rows under ON UPDATE CASCADE, while the NO ACTION default and RESTRICT reject the update instead.
Code
CREATE TABLE product_codes (
code text PRIMARY KEY
);
CREATE TABLE stock_items (
item_id int PRIMARY KEY,
code text NOT NULL REFERENCES product_codes (code) ON UPDATE CASCADE
);
INSERT INTO product_codes VALUES ('SKU-001'), ('SKU-002');
INSERT INTO stock_items VALUES (10, 'SKU-001'), (11, 'SKU-002'), (12, 'SKU-001');
-- 自然键改名:ON UPDATE CASCADE 把 child 表的引用列 ripple 一起改掉
UPDATE product_codes SET code = 'SKU-1001' WHERE code = 'SKU-001';
SELECT item_id, code FROM stock_items ORDER BY item_id;
-- 两行 SKU-001 同步变成 SKU-1001,引用不断裂
-- 默认 NO ACTION 与 RESTRICT:更新被引用的键直接拒绝
CREATE TABLE stock_restrict (
item_id int PRIMARY KEY,
code text NOT NULL REFERENCES product_codes (code) ON UPDATE RESTRICT
);
INSERT INTO stock_restrict VALUES (20, 'SKU-002');
-- UPDATE product_codes SET code = 'SKU-2002' WHERE code = 'SKU-002';
-- ERROR: update or delete on table "product_codes" violates foreign key constraint
DROP TABLE stock_restrict;
DROP TABLE stock_items;
DROP TABLE product_codes;Inside the snippet
What runs here is SELECT / INSERT / UPDATE / CREATE — cascade, product_codes, stock_items, restrict and stock_restrict are the objects involved.
Breaking the statements into their working parts: a WHERE clause narrowing which rows one statement affects; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; a foreign-key REFERENCES guard tying rows to the parent table.
Putting it to use
The cascade table is the working surface here.
Core lines
CREATE TABLE stock_restrict (
item_id int PRIMARY KEY,
code text NOT NULL REFERENCES product_codes (code) ON UPDATE RESTRICT
);
CREATE TABLE stock_items (
item_id int PRIMARY KEY,
code text NOT NULL REFERENCES product_codes (code) ON UPDATE CASCADE
);
UPDATE product_codes SET code = 'SKU-1001' WHERE code = 'SKU-001';
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.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- What relations does the SQL touch?
- `cascade`, `product_codes`, `stock_items`, `restrict`, `stock_restrict` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.