Now, what happens when you have successfully created a reference, and now you try deleting the parent? This is where the ON DELETE clause come in. This is essentially how we configure how strict a foreign key is.
There are 3 options you can give for an ON DELETE:
RESTRICT / NO ACTION Yes - In MySQL they are the same, but not all DBMS.
SET NULL Yes
Now the default is RESTRICT. This means that when you try to delete a parent row, MySQL is going to throw an error and not let you.
Cascade means that if you delete the parent row, any rows that reference that parent will also be deleted. This is pretty dangerous and not often recommended.
SET NULL will set the foreign key to be NULL. Now obviously, this is going to require that the foreign key is not labelled NOT NULL.
In addition to the ON DELETE clause, there is the ON UPDATE clause. This one is a little less common because it configures what happens when a parent value changes. Obviously, when you are referencing a primary key, the ON UPDATE clause is nearly useless. That's because the primary key value is never supposed to change. If, on the other hand, we have a foreign key referencing a UNIQUE column that is not a primary key, it may change occasionally. So the only times you have to worry about the ON UPDATE clause is with foreign keys referencing UNIQUE columns that are not a primary key, and when you have natural keys that break the rules and actually do change at some point in time. The ON UPDATE clause has the same options as the ON DELETE clause and they all work the same way.
Now, the last thing you need to know about foreign keys is that they must match the data type of the column you are referencing.
Support me! http://www.patreon.com/calebcurry
Subscribe to my newsletter: http://bit.ly/JoinCCNewsletter
More content: http://CalebCurry.com
Amazing Web Hosting - http://bit.ly/ccbluehost (The best web hosting for a cheap price!)