Data Modeling - Foreign Key Constraint

> (Data|State) Management and Processing > Data Modeling (Relational Database, Code, Graph, Text)

1 - About

A Foreign Key is a constraint on :

  • a column
  • or combination of columns

used to establish and enforce a one to many relationship between data in two tables.

This is also known as foreign key/primary key relationships

The link is created between the two tables by defining on the foreign table the column (or columns) that hold data from an other table's primary key values.

Referential Integrity is a data property whereby a Foreign Key in one table has a corresponding Primary key in a different table.

Advertising

3 - Pro / cons

  • sharding: Extracting data with foreigns keys is hard and therefore sharding is hard
  • Performance: An index lookup is executed for each insert/delete

4 - Example

An Foreign Key example of a database (with the scott schema from Oracle).

Consider a part of the EMP (Employe) table.

EMPNO ENAME DPTNO
7369 SMITH 10
7499 ALLEN 20
7566 JONES 30

The column DPTNO from the EMP table refer to the column DEPTNO from the table DEPT (Department) below :

DEPTNO DNAME
10 ACCOUNTING
20 RESEARCH
30 DISTRIBUTION

For each DPTNO in the table EMP, you must have a DPTNO in the table DEPT. We say then that :

  • the column DPTNO from the table EMP is a foreign key.
  • and then that the column DEPTNO is a primary key.

If it's not true, there is NO referential integrity.

Advertising

5 - Documentation