TATECHATLAS
◎ English
Data & databases / Guide

PostgreSQL foreign keys: NO ACTION timing and selective SET NULL

A closer look at explicitly deferred NO ACTION checks and clearing only the optional component of a composite foreign key. These details complement the basic choice between RESTRICT, CASCADE and SET NULL.

On this page

NO ACTION is the default delete action, but NOT DEFERRABLE is the default constraint setting. Deferral therefore requires an explicit DEFERRABLE declaration. RESTRICT cannot defer its delete check. For composite SET NULL, select only nullable columns that may be cleared, and check the remaining primary-key and matching constraints.

Frame the delete policy as a data-retention decision

Every foreign key carries an implicit answer to a business question: when the referenced row disappears, what should happen to the rows that point at it? ON DELETE RESTRICT answers that the dependents must survive and the parent cannot be removed until those dependents are handled explicitly. ON DELETE CASCADE answers that the dependents are inseparable parts of the parent and should vanish together. ON DELETE SET NULL answers that the reference is optional and the dependent row can continue to exist without it. These are not interchangeable syntax options; they encode retention rules that affect what data remains queryable after a delete.

The PostgreSQL documentation states that the actions reflect intuitive choices: disallow deleting a referenced product, delete the orders as well, or something else. Picking the wrong one can silently remove rows that another relationship would need to preserve, or can block legitimate cleanup because dependents were never intended to survive.

This decision should follow the meaning of the relationship, not the convenience of the schema author. A product catalog entry referenced by historical orders is not the same as an order-item line that exists only because the order exists.

CREATE TEMP TABLE products (product_no integer PRIMARY KEY);
CREATE TEMP TABLE orders (order_id integer PRIMARY KEY);
CREATE TEMP TABLE order_items (
  product_no integer REFERENCES products ON DELETE RESTRICT,
  order_id integer REFERENCES orders ON DELETE CASCADE,
  PRIMARY KEY (product_no, order_id)
);
INSERT INTO products VALUES (7);
INSERT INTO orders VALUES (42);
INSERT INTO order_items VALUES (7,42);

Inspect constraints and count dependents first; demonstrate timing and selective SET NULL in isolated temporary examples. Review locks, triggers and downstream retention rules separately before planning a production migration.

Read the default NO ACTION behavior before changing it

Omitting ON DELETE selects NO ACTION, not automatic deferral. By default the constraint is NOT DEFERRABLE and checks are not postponed to transaction end. A NO ACTION foreign key declared DEFERRABLE INITIALLY DEFERRED can temporarily lose its parent if the relationship is repaired before the final check. RESTRICT cannot postpone the delete check. The independent temporary-table example deletes and restores parent 7 in one transaction, leaving the child reference valid at commit. The final SELECT is expected to return one child referencing 7. This is an illustration of timing, not a recommendation to manipulate production identifiers.

CREATE TEMP TABLE fk_parent (id integer PRIMARY KEY);
CREATE TEMP TABLE fk_child (
  id integer PRIMARY KEY,
  parent_id integer REFERENCES fk_parent(id)
    ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED
);
INSERT INTO fk_parent VALUES (7);
INSERT INTO fk_child VALUES (1,7);
BEGIN;
DELETE FROM fk_parent WHERE id=7;
INSERT INTO fk_parent VALUES (7);
COMMIT;
SELECT id,parent_id FROM fk_child;

Choose RESTRICT when referenced rows must survive

For the seeded products example, an attempted deletion of product 7 is blocked because order 42 contains a matching item. Without this seed, deleting a nonexistent product would affect zero rows and would not demonstrate RESTRICT. Use RESTRICT when the intended policy requires existing dependents to be handled explicitly; it is not a universal policy for all master data. The database error category is a foreign-key violation; exact text and constraint names depend on the schema and client.

-- In the initial seeded state, this attempted delete is rejected:
-- DELETE FROM products WHERE product_no=7;

Choose CASCADE only for dependent lifecycle rows

ON DELETE CASCADE is appropriate when child rows exist only as part of the parent's lifecycle and have no independent meaning. The documentation notes that order items are part of an order, and it is convenient if they are deleted automatically if an order is deleted. The cascade travels from the referenced row to every referencing row in one operation.

The danger is that CASCADE can remove data that a different relationship would need to preserve. If an order_item row is also referenced by a shipping manifest or an audit log, cascading the delete from orders will remove the order_item and then violate or cascade further along those other foreign keys. Use CASCADE only when you have traced every downstream reference and confirmed that automatic removal is the intended behavior for all of them.

-- Deleting an order cascades to its line items:
DELETE FROM orders WHERE order_id = 42;
-- All rows in order_items with order_id = 42 are removed automatically.

Choose SET NULL only for optional references

The composite example is independent and uses temporary tables in a disposable PostgreSQL 18 session. User (1,7) owns post (1,42). Deleting that user clears author_id only, leaving tenant_id=1 and post_id=42. The final query is expected to return (1,42,NULL). Clearing both key columns would violate the post primary key. The example uses default MATCH SIMPLE; MATCH FULL would reject a partly null composite reference. SET NULL must also satisfy other NOT NULL and CHECK constraints.

CREATE TEMP TABLE tenants (tenant_id integer PRIMARY KEY);
CREATE TEMP TABLE users (
  tenant_id integer REFERENCES tenants,
  user_id integer,
  PRIMARY KEY (tenant_id,user_id)
);
CREATE TEMP TABLE posts (
  tenant_id integer REFERENCES tenants,
  post_id integer,
  author_id integer,
  PRIMARY KEY (tenant_id,post_id),
  FOREIGN KEY (tenant_id,author_id) REFERENCES users(tenant_id,user_id)
    ON DELETE SET NULL (author_id)
);
INSERT INTO tenants VALUES (1);
INSERT INTO users VALUES (1,7);
INSERT INTO posts VALUES (1,42,7);
DELETE FROM users WHERE tenant_id=1 AND user_id=7;
SELECT tenant_id,post_id,author_id FROM posts;

Compare the three actions on one small schema

Read each action comparison from the initial seeded state, not after executing all prior deletes cumulatively. Deleting product 7 is blocked while its item exists; deleting order 42 removes that item through CASCADE. A shipper example would need an additional shipper table and an optional foreign key before its outcome could be claimed.

Verify the policy before applying it to real data

Inspect the schema and count relevant dependents using SELECT first. Try changes in a disposable database or isolated copy with representative rows, not against live tables. ROLLBACK reverses transactional database changes, but a statement can still hold locks or trigger external effects that are not reversible. After a constraint error, roll back the aborted transaction before continuing. Successful behavior on a small copy is not evidence that a production constraint migration is free of locking or data-retention issues.

Know when the policy is insufficient

Trace downstream foreign keys and triggers before changing delete policy. Keep any example of a delete without a filter as an explanation, not an executable production command. A constraint controls references, not the entire retention policy. ON UPDATE has different restrictions; the subset-column syntax shown here applies to ON DELETE.

Things to check

  • NO ACTION and NOT DEFERRABLE defaults are distinguished
  • Deferral is explicitly configured; RESTRICT delete checks are not deferred
  • Expected outcomes include actual initial rows and are considered independently
  • Composite SET NULL clears only author_id and preserves the tenant key
  • Demonstrations use an isolated copy; rollback is not a blanket safety guarantee

Examples target PostgreSQL 18 and assume a disposable session. NO ACTION deferral requires explicit DEFERRABLE configuration. Selective SET NULL with default MATCH SIMPLE still must satisfy other constraints. ROLLBACK does not promise absence of locks or irreversible external effects.

Sources

  1. PostgreSQL: foreign keys ↗
  2. PostgreSQL: CREATE TABLE and deferral defaults ↗
  3. PostgreSQL: SET CONSTRAINTS ↗
Back to top ↑