What is a Foreign Key?

A foreign key is a field that is linked to another table‘s primary key field in a relationship between two tables.

In relational database management systems, a relationship defines a relationship between two or more tables. That is, the data in one table is related to the data in the other. One table contains the primary key and the other table contains the foreign key.

When we establish a relationship between the tables, we link the foreign key with the primary key. From that point on, any value in the foreign key field should match a value from the primary key field in the other table.

Diagram of one-to-many relationship
Example of a one-to-many relationship. The CityId in the Customer table is the foreign key.

In the above example, the CityId field in the Customer table is a foreign key. It is linked to the CityId field in the City table which is a primary key. For any given record, the value of Customer.CityId will match the value of City.CityId.

So foreign keys are an essential part of relational database systems. Without foreign keys, we wouldn’t be able to match data in one table with data from another. At least, we wouldn’t be able to match it with full confidence that the results are correct. This is because the value of the primary field  is a unique identifier.

Therefore, the value of the foreign key field is the unique identifier for the record in the other table. So we know that the foreign key value refers to only that single record.