How to add "on delete cascade" constraints?
I'm pretty sure you can't simply add on delete cascade
to an existing foreign key constraint. You have to drop the constraint first, then add the correct version. In standard SQL, I believe the easiest way to do this is to
- start a transaction,
- drop the foreign key,
- add a foreign key with
on delete cascade
, and finally - commit the transaction
Repeat for each foreign key you want to change.
But PostgreSQL has a non-standard extension that lets you use multiple constraint clauses in a single SQL statement. For example
alter table public.scores
drop constraint scores_gid_fkey,
add constraint scores_gid_fkey
foreign key (gid)
references games(gid)
on delete cascade;
If you don't know the name of the foreign key constraint you want to drop, you can either look it up in pgAdminIII (just click the table name and look at the DDL, or expand the hierarchy until you see "Constraints"), or you can query the information schema.
select *
from information_schema.key_column_usage
where position_in_unique_constraint is not null
Based off of @Mike Sherrill Cat Recall's answer, this is what worked for me:
ALTER TABLE "Children"
DROP CONSTRAINT "Children_parentId_fkey",
ADD CONSTRAINT "Children_parentId_fkey"
FOREIGN KEY ("parentId")
REFERENCES "Parent"(id)
ON DELETE CASCADE;