CREATE TABLE PKTABLE (
tid int,
id int,
PRIMARY KEY (tid, id)
);
CREATE TABLE FKTABLE (
tid int,
id int,
fk_id_del_set_null int,
fk_id_del_set_default int DEFAULT 0,
FOREIGN KEY (tid, fk_id_del_set_null) REFERENCES PKTABLE ON DELETE SET NULL (fk_id_del_set_null),
FOREIGN KEY (tid, fk_id_del_set_default) REFERENCES PKTABLE ON DELETE SET DEFAULT (fk_id_del_set_default)
);
INSERT INTO PKTABLE
VALUES (1, 0),
(1, 1),
(1, 2);
INSERT INTO FKTABLE
VALUES (1, 1, 1, NULL),
(1, 2, NULL, 2);
DELETE FROM PKTABLE
WHERE id = 1
OR id = 2;
SELECT
*
FROM
FKTABLE
ORDER BY
id;
Primary key(tid,id) means both column cannot be NULL.
Unique(tid,id) means it accept (tid null,id null), (tid not null, id null), (tid null, id not null). demo
Other than that, all the same. Primary key will create index, unique contsraint will also create index. see manual
So overall, if you use primary key, you don't need to care about both two column will be null or not.
And in pg15 (link), in foreign key you can
FOREIGN KEY (tid, fk_id_del_set_null) REFERENCES PKTABLE ON DELETE SET NULL (fk_id_del_set_null)
Which means that you tenant_id will always exists in all the table related to that tenant_id.