Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Create Trigger Before Delete vs. Foreign Key On Delete

I have one table referencing another. As I see - there are two ways to delete cascading:

What is the difference between CREATE TRIGGER BEFORE DELETE and FOREIGN KEY ON DELETE? Are there any differences in performance?

I came up with this advantage of FOREIGN KEY:
The cascading delete is more obvious because it's attached in the table definition.

Full question:
I have the two tables:
project(id, ...) <- works_on(id, project_id, ...)

What are the differences in

CREATE TABLE works_on (
  ...
  FOREIGN KEY (project_id) REFERENCES project ON DELETE CASCADE
  ...
);

and

CREATE TRIGGER trigger_delete_cascading
  BEFORE DELETE ON project
  DELETE works_on
    WHERE project_id = id;
like image 518
SUhrmann Avatar asked Jun 09 '26 07:06

SUhrmann


2 Answers

A FOREIGN KEY will restrict values that can be stored in the project_id column of the works_on table. You will not be able to set a value that does not exist in the project table.

A TRIGGER does not restrict the range of values that can be stored.

like image 142
Serge Avatar answered Jun 11 '26 21:06

Serge


If wrote trigger BEFORE delete,will DELETE record from CHILD TABLE and due to some Server error or Other constraint if record is unable to delete from MAIN TABLE(PARENT) then it makes redundant data. So whenever you required delete plus more action like maintaining LOG table then only you have to go with Trigger.Otherwise ON DELETE CASCADE is great to work. Hope this will helps you.

like image 20
Sagar Gangwal Avatar answered Jun 11 '26 21:06

Sagar Gangwal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!