Foreign Key Referential Actions

Show what ON DELETE CASCADE, RESTRICT, and SET NULL do to child rows, and why NO ACTION differs from RESTRICT by allowing DEFERRABLE checks.

SqlData Integrity

Code

snippet
-- referential action 决定删除父行时子行的命运:CASCADE 级联、RESTRICT 拒绝、SET NULL 置空
CREATE TABLE projects (project_id integer PRIMARY KEY);

CREATE TABLE tasks_cascade (
  task_id    integer PRIMARY KEY,
  project_id integer NOT NULL,
  CONSTRAINT fk_tasks_cascade FOREIGN KEY (project_id)
    REFERENCES projects (project_id) ON DELETE CASCADE
);
CREATE TABLE tasks_restrict (
  task_id    integer PRIMARY KEY,
  project_id integer NOT NULL REFERENCES projects (project_id) ON DELETE RESTRICT
);

INSERT INTO projects VALUES (1), (2);
INSERT INTO tasks_cascade VALUES (201, 1);
INSERT INTO tasks_restrict VALUES (101, 2);

-- CASCADE:删除父行 1,子行 201 一并消失
DELETE FROM projects WHERE project_id = 1;
SELECT count(*) FROM tasks_cascade;

-- RESTRICT:子行 101 还在,删除父行 2 会直接报错:
-- DELETE FROM projects WHERE project_id = 2;
-- NO ACTION 与 RESTRICT 的区别:NO ACTION 允许 DEFERRABLE,检查可推迟到 COMMIT
SELECT project_id FROM projects;

Inside the snippet

Several statements share this file — SELECT / INSERT / DELETE / CREATE, with projects, tasks_cascade and tasks_restrict among the objects involved.

Breaking the statements into their working parts: a WHERE clause narrowing which rows one statement affects; 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.

Putting it to use

The projects table is the working surface here.

Core lines

CREATE TABLE tasks_cascade (
task_id    integer PRIMARY KEY,
project_id integer NOT NULL,
CONSTRAINT fk_tasks_cascade FOREIGN KEY (project_id)
REFERENCES projects (project_id) ON DELETE CASCADE
);
CREATE TABLE tasks_restrict (
task_id    integer PRIMARY KEY,
project_id integer NOT NULL REFERENCES projects (project_id) ON DELETE RESTRICT
);
CREATE TABLE projects (project_id integer PRIMARY KEY);

Interactive Tools for This Topic

FAQ

Which tables or CTEs does it reference?
The references are `projects`, `tasks_cascade`, `tasks_restrict`.