Foreign Key
In one line
A foreign key is a column in one table that references the primary key of another table, creating a link between the two.
In simple words
A foreign key is how you connect rows in one table to rows in another. The foreign key column holds a value that must match the primary key of a row in the referenced table.
For example, if an orders table has a user_id column that references users(id), then each order is linked to the user who placed it. The database enforces this — you cannot insert an order with a user_id that does not exist in the users table.
Foreign keys enforce referential integrity: you cannot delete a user who still has orders (unless you set up cascading deletes), and you cannot create an orphan order pointing to a non-existent user.
Example
CREATE TABLE orders (
id SERIAL PRIMARY KEY,
user_id INTEGER REFERENCES users(id),
total NUMERIC(10,2)
);
-- user_id is a foreign key pointing to users.idThe user_id foreign key ensures every order is linked to a real user — no orphan orders.
Common confusions
Confused with: primary key
The difference: A primary key uniquely identifies rows in this table; a foreign key points to the primary key of another table. A column can be both, but they serve different purposes.
Related terms
Related Resources
Related Lessons
- Relationships
Learn how foreign keys create table relationships.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.