Deferrable Foreign Key Insert Order

Declare a foreign key DEFERRABLE INITIALLY DEFERRED so child rows can be inserted before their parents and the check happens once at COMMIT.

SqlData Integrity

Code

snippet
-- 外键声明为 DEFERRABLE INITIALLY DEFERRED:检查推迟到 COMMIT,
-- 数据装载脚本就可以先插子行、再补父行
CREATE TABLE customers (
    id    bigint PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
    email text NOT NULL UNIQUE
);

CREATE TABLE invitations (
    id          bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    customer_id bigint REFERENCES customers DEFERRABLE INITIALLY DEFERRED,
    sent_at     timestamptz NOT NULL DEFAULT now()
);

BEGIN;
-- 子行先插入:FK 校验被推迟,父行随后补上
INSERT INTO invitations (customer_id) VALUES (42);
INSERT INTO customers (id, email) VALUES (42, '[email protected]');
COMMIT;

-- 校验通过后再查一次关联,确认父子行都落库
SELECT c.email, i.sent_at
FROM invitations i
JOIN customers c ON c.id = i.customer_id;

-- 若父行最终缺失,COMMIT 时才报错:
-- ERROR: insert or update on table "invitations" violates foreign key constraint

How it works

Several statements share this file — SELECT / INSERT / CREATE, with invitations and customers among the objects involved.

Mechanically, the statements are built from: one JOIN combining rows across tables; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; UNIQUE constraints that keep duplicate values out; DEFAULT values filling omitted columns; a GENERATED ALWAYS/GENERATED BY clause that computes the column value; a foreign-key REFERENCES guard keeping child rows pointed at the parent table.

Putting it to use

Run the statement against the invitations table.

Core lines

SELECT c.email, i.sent_at
FROM invitations i
JOIN customers c ON c.id = i.customer_id;
CREATE TABLE invitations (
    id          bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    customer_id bigint REFERENCES customers DEFERRABLE INITIALLY DEFERRED,
    sent_at     timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE customers (
    id    bigint PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
    email text NOT NULL UNIQUE
);

Interactive Tools for This Topic

FAQ

Which relations are involved here?
The references are `invitations`, `customers`, with one join tying the pair together.