Two Foreign Keys One Parent Roles

Point two FOREIGN KEY columns at the same parent table and give each a role name plus its own ON DELETE behavior, so sender and receiver stay distinct.

SqlData Integrity

Code

snippet
CREATE TABLE accounts (
    account_id int PRIMARY KEY,
    name       text NOT NULL
);

-- 同一张父表被两列引用:每列一个角色,删除行为各自声明
CREATE TABLE transfers (
    transfer_id  int PRIMARY KEY,
    amount_cents int NOT NULL CHECK (amount_cents > 0),
    sender_id    int NOT NULL REFERENCES accounts (account_id) ON DELETE RESTRICT,
    receiver_id  int NOT NULL REFERENCES accounts (account_id) ON DELETE CASCADE,
    CHECK (sender_id <> receiver_id)
);

INSERT INTO accounts (account_id, name) VALUES (1, 'ada'), (2, 'lin');

INSERT INTO transfers (transfer_id, amount_cents, sender_id, receiver_id)
VALUES (1, 2500, 1, 2);

-- 违反 sender <> receiver 的自转账被 CHECK 当场拒绝
INSERT INTO transfers (transfer_id, amount_cents, sender_id, receiver_id)
VALUES (2, 100, 1, 1);

-- 删除演示:RESTRICT 挡住还有转账引用的发送方,CASCADE 连带清掉接收方的转账
DELETE FROM accounts WHERE account_id = 1;

DROP TABLE transfers, accounts;

Inside the snippet

Several statements share this file — INSERT / DELETE / CREATE, with accounts and transfers among the objects involved.

In terms of clauses, the statements use: a WHERE clause narrowing which rows one statement affects; a CHECK constraint that rejects out-of-domain values at write time; 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

Run the statement against the accounts table.

Core lines

CREATE TABLE transfers (
transfer_id  int PRIMARY KEY,
amount_cents int NOT NULL CHECK (amount_cents > 0),
sender_id    int NOT NULL REFERENCES accounts (account_id) ON DELETE RESTRICT,
receiver_id  int NOT NULL REFERENCES accounts (account_id) ON DELETE CASCADE,
CHECK (sender_id <> receiver_id)
);
INSERT INTO transfers (transfer_id, amount_cents, sender_id, receiver_id)
VALUES (1, 2500, 1, 2);
INSERT INTO transfers (transfer_id, amount_cents, sender_id, receiver_id)
VALUES (2, 100, 1, 1);

Interactive Tools for This Topic

FAQ

Which tables does the SQL touch?
`accounts`, `transfers` — referenced directly, no join needed.