Database Basics - Foreign Keys

 

A foreign key is a relationship or link between two tables which ensures that the data stored in a database is consistent.

 

The foreign key link is set up by matching columns in one table (the child) to the primary key columns in another table (the parent).

 

How do I set up a foreign key?

 

Example:

In the example below, there is a link between the Company and Contact tables.  The Company table is the parent table in the link.  The Contact table is the child: the Company_ID field in the Contact table indicates which Company a Contact belongs to.

 

Child Role (Multiplicity):

The multiplicity of a foreign key defines how many records in the child table can link to a record in the parent table.  In the example above the child multiplicity is "many" since one company can have any number of contacts.

Cascade Deletes:

Each child record in a foreign key relationship must have a matching parent record.  A user of your database will not be allowed to delete a Company that has Contacts linked to it unless the foreign key is set up to do a cascade delete.  The cascade delete option means that whenever a record in the parent table is deleted, every matching record in the child table is also deleted.

 

Related Topics: