liveBook · Manning

Foreign key

As explained in Grokking Software Architecture

A foreign key is a relational database column or set of columns that references a key in another table to represent a relationship between records.

A foreign key (FK) is an explicitly defined constraint that links a column in one table to a key in another. It acts like a guard dog: it rejects references to records that do not exist, helping prevent orphaned data. section 8.2.1

Orders and customers

Orders.CustomerId can reference Customers.Id, the primary key of the Customers table. Naming the column CustomerId is not enough: the database must have an explicit foreign key constraint. Once defined, it refuses an order for a nonexistent customer and can prevent deleting a customer who still has orders. section 8.2.1

Figure 8.2 Showing how Primary Keys and Foreign Keys work together to link tables. The child table (Orders) uses the Customer_ID as a Foreign Key to point directly back to its parent record (Customers), establishing a clear one-to-many relationship.

See how the Orders foreign key points to a Customers primary key in a one-to-many relationship. section 8.2.1

Foreign keys also help link data stored in separate tables. For example, an address can be stored once and linked to orders instead of being duplicated in every order. section 8.2.1

How Grokking Software Architecture covers it

How deep it goes
Defines the constraint and explains invalid writes and parent deletion, without showing constraint-creation syntax.
Examples
Uses customer orders and a shared address to illustrate references and reduced duplication.
What you can do after
Evaluate whether a named column has an explicit foreign key constraint and understand its integrity role.
How it connects
Connects primary keys, normalization, one-to-many relationships, and orphaned data.

Also explained in

Compare how 21 books explain foreign key →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Grokking Software Architecture. The section links point to the parts of the book it draws on.