Search code examples
postgresqlforeign-keys

Postgres allows duplicate foreign keys one with cascade delete one without. Does that makes sense?


I am working on an existing Postgres 13.x DB I noticed these two FK in an ER Diagram. Does it make sense to have both of these? They seem to contradict each other. Just one of these FK would make sense to me and not both. Any harm in having both? I am surprised Postgres allows both.

ALTER TABLE table_x ADD CONSTRAINT fk_x_1
FOREIGN KEY (field_x) REFERENCES table_x(unid);
ALTER TABLE table_x ADD CONSTRAINT fk_x_2
FOREIGN KEY (field_x) REFERENCES table_x(unid) ON DELETE CASCADE;

Solution

  • You can create both foreign key constraints, but it doesn't make any sense. Either you want deletes to cascade to the referencing table or not.

    Still, it makes sense to allow both constraints: imagine you have a foreign key constraint without cascading delete, and you want to convert it to cascading delete. Since there is no ALTER CONSTRAINT, you'd have to create the new constraint, then drop the old one, to ensure that the foreign key relationship can never be violated.