Chapter 14: Data and failure

Foreign key

A column in one table that must match the primary key of a row in another. An order's customer_id has to point at a real customer. The database refuses anything that would leave it pointing at nothing, and you choose what happens when the row it points at is deleted.

Without one, nothing stops an order pointing at a customer who no longer exists, and an agent writing a clean-up script will happily create thousands of them. With one, choose the delete rule yourself. An agent adding CASCADE to fix an error has decided that deleting one customer may silently delete their whole history.

Say it to your agent

“Make orders.customer_id a foreign key to customers.id with ON DELETE RESTRICT. Don't add CASCADE to make an error go away. If a customer must be deletable, ask me what should happen to their orders first.”

The workshop

Name a word, or describe what you mean in everyday language.