No Action Deferrable Versus Restrict
NO ACTION with DEFERRABLE lets the parent delete succeed until commit, while RESTRICT rejects the same statement immediately even when deferred.
Code
-- 关键差异:NO ACTION 可推迟到提交才检查;RESTRICT 即使声明 DEFERRABLE 也当场拦截
CREATE TABLE parents (id int PRIMARY KEY);
INSERT INTO parents VALUES (1);
CREATE TABLE children_noaction (
id int PRIMARY KEY,
parent_id int NOT NULL REFERENCES parents (id)
ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED
);
CREATE TABLE children_restrict (
id int PRIMARY KEY,
parent_id int NOT NULL REFERENCES parents (id)
ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED
);
INSERT INTO children_noaction VALUES (10, 1);
INSERT INTO children_restrict VALUES (20, 1);
-- NO ACTION + DEFERRABLE:DELETE 语句本身成功,违例推迟到 COMMIT 才报错
BEGIN;
DELETE FROM parents WHERE id = 1;
SELECT count(*) AS noaction_child_alive FROM children_noaction; -- 子行还在
ROLLBACK;
-- RESTRICT:同样声明了 DEFERRABLE,DELETE 仍当场失败:
-- DELETE FROM parents WHERE id = 1;
-- ERROR: update or delete on table "parents" violates foreign key
-- constraint "children_restrict_parent_id_fkey" on table "children_restrict"
DROP TABLE children_restrict;
DROP TABLE children_noaction;
DROP TABLE parents;How it works
What runs here is SELECT / INSERT / DELETE / CREATE — parents, children_noaction and children_restrict are the objects involved.
Breaking the statements into their working parts: a WHERE clause filtering the rows one statement applies to; COUNT aggregation; 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.
Applying it
Run the statement against the parents table.
Statements that matter
CREATE TABLE children_noaction (
id int PRIMARY KEY,
parent_id int NOT NULL REFERENCES parents (id)
ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED
);
CREATE TABLE children_restrict (
id int PRIMARY KEY,
parent_id int NOT NULL REFERENCES parents (id)
ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED
);
SELECT count(*) AS noaction_child_alive FROM children_noaction; -- 子行还在
Interactive Tools for This Topic
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.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.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?
- `parents`, `children_noaction`, `children_restrict`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.