I have several tables which reference one main table using foreign keys.
My goal is for one blanket delete statement from the main table, which will then delete all those with the data as foreign keys as well.
However I get constraint errors as I expect since the reference is deleted before its deleted from the other tables. Is there any way to tell SQL I would like to delete from all tables where the data is used as a foreign key as well?
To have deletes on the parent table cascade to referencing tables, use an
ON DELETE CASCADEforeign key. However, if you’re deleting all rows from the main table there’s a better way to solve your problem usingTRUNCATE; see the end of this post.You can
ALTER TABLEto change a defaultON DELETE NO ACTIONforeign key toON DELETE CASCADE. Drop the constraint then re-create it with theON DELETE CASCADEmodifier. SeeCREATE TABLEand the constraints documentation for information on the foreign key constraint syntax.In brief, instead of
col coltype REFERENCES fktable(fkcol)you usecol coltype REFERENCES fktable(fkcol) ON DELETE CASCADE.If you use
ON DELETE CASCADEthen to get even vaguely decent performance it is vital to create an index on the foreign key column. Even then, for bulk deletes from the target table it’s often much faster to go and delete from each foreign key referencing table first, rather than relying on cascades.You may want to also use
ON UPDATE CASCADEif you’re usingON DELETE CASCADE.If you’re deleting all rows from the main table, not just a selection of them, you’re probably better off truncating the tables with
TRUNCATE ... CASCADE: