Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should you make a self-referencing table column a foreign key?

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?

like image 295
meleyal Avatar asked Oct 29 '08 11:10

meleyal


People also ask

Can foreign key reference own table?

FOREIGN KEY constraints can reference only tables within the same database on the same server.

What is a self-referencing foreign key?

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.

Why foreign key is not recommended?

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.

Which table should hold foreign key?

As a rule of thumb, you should add a foreign key on the child table referencing the parent table.


2 Answers

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.

like image 98
Mikezx6r Avatar answered Sep 19 '22 19:09

Mikezx6r


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:

  • Assuming the proper design of the relationships, foreign key constraints make it more difficult for a programmer to introduce an inconsistency into the database.
  • Centralizing the checking of these constraints by the database server makes it unnecessary to perform these checks on the application side. This eliminates the possibility that different applications may not check constraints in the same way.
  • Using cascading updates and deletes can simplify the application code.
  • Properly designed foreign key rules aid in documenting relationships between tables.

The disadvantages:

  • If you define Foreign Keys, sometimes it is harder to perform bulk operations.
  • Maybe it implies more disk usage and a slight performance hit.
like image 41
Guido Avatar answered Sep 21 '22 19:09

Guido