What is a foreign key?

A foreign key is a column that points to a row in another table. It's how the database knows that two pieces of data are related.

Example

Your app has two tables: users and notes. Each note belongs to a user. The notes table has a user_id column that references users.id:

users table          notes table
┌────┬───────┐       ┌────┬─────────┬────────┐
│ id │ email │       │ id │ user_id │ title  │
├────┼───────┤       ├────┼─────────┼────────┤
│  1 │ alice │       │  1 │       1 │ Note A │
│  2 │ bob   │       │  2 │       1 │ Note B │
└────┴───────┘       │  3 │       2 │ Note C │
                     └────┴─────────┴────────┘

Notes 1 and 2 belong to Alice (user_id = 1). Note 3 belongs to Bob (user_id = 2).

What the database enforces

If you try to create a note with user_id = 99 and there's no user with id 99, the database rejects it. The foreign key constraint guarantees every note points to a real user.

This is how user-linked data works — every row in the notes table is tied to a specific user through the foreign key.