Skip to content
>devspeak
← glossary
level 4Databases

Foreign key

also: foreign keys, foreign-key, fk

A column that points to a row in another table by storing that row's ID. For example, each order stores the ID of the customer who placed it.

a bit more technical

A column (or set of columns) whose values must match the primary key, or another unique key, of a row in another table or occasionally the same table. The database enforces the reference: it rejects values that point to nothing and controls what happens on delete.

picture it

A coat-check ticket. The number points to exactly one coat. A ticket for a coat that doesn't exist is a problem, so the coat check never hands those out.

why it matters

Foreign keys are how your app knows which data belongs together. Errors mentioning them usually mean data points at something missing. That matters most when you're deleting or migrating data.

what your agent might say
agent
The insert failed with a foreign key violation: order_items references product 902, which doesn't exist in products.
how you might use it
you → your agent
Before deleting old products, check which tables have foreign keys pointing to them, and tell me what would happen to those rows.
common mistake

Thinking a foreign key is a second kind of ID for the row it's in. It's a pointer. It stores another table's key value, usually its primary key.