What is the difference between relating 2 tables using and not using a foreign key
?
A: The difference is that when you do not use foreign key
to relate your tables to the constraint of the relationship if it exists, it will have to be controlled by your application, this can be a big disadvantage because integrity check of your tables will be decentralized differently than when the database server controls the integrity of the relationships.
Regarding performance, is it recommended to use foreign key
to make the relationship?
R: When we set a foreign key
what the database server actually does is create an internal trigger
, so you can check the referential integrity of each inserted, updated, or deleted row . This leads to overhead in the execution of batch operations, for example where many changes are processed by the server in an operation, imagine that your application will do a data import of movements of a supermarket where thousands of sales happen in a day; in these types of situations the use of foreign keys
affects a lot in performance, what many programmers usually do is disable checking foreign key
before costly operations, eg mysql:
SET foreign_key_checks = 0;
In what situation would it be indispensable and in what situation would it be unnecessary to use a foreign key
to make the relationship?
R: This depends a lot on the business rule of your application but in general are indispensable when the existence of the entity of a table depends on another and this has great importance in the system and is also accessed different locations in the application; requiring centralization. Now tables where foreign keys
are expendable may be for secondary register entities that do not have great importance in the application, but that depends a lot.
Reference: link