For example to create a hierarchy of categories you use a column 'parent_id', which points to another category in the same table.
Should this be a foreign key? What would the dis/advantages be?
FOREIGN KEY constraints can reference only tables within the same database on the same server.
A self-referencing constraint exists if a Db2® object is subject to a primary or foreign key relationship in which the parent table and the dependent table are the same table. If the DELETE rule for the relationship is CASCADE, the deletion or change of one row can cause a recursive deletion of other rows in the table.
Having active foreign keys on tables improves data quality but hurts performance of insert, update and delete operations. Before those tasks database needs to check if it doesn't violate data integrity. This is a reason why some architects and DBAs give up on foreign keys at all.
As a rule of thumb, you should add a foreign key on the child table referencing the parent table.
Yes. Ensures that you don't have an orphan (entry with no parent), and depending on usage, if you define a cascading delete, when a parent is deleted, all its children will also be deleted.
Disadvantage would be a slight performance hit just like any other foreign key.
Yes, you should. If you have an attribute in a relation of database that serves as the primary key of another relation in the same database you should make it a FK.
You will enjoy the advantages associated to foreign keys:
The disadvantages:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With