Foreign Key
ELI5 — The Vibe Check
A foreign key is how you link two tables together. If an 'orders' table has a 'user_id' column pointing to the 'users' table, that is a foreign key. It is like saying 'this order belongs to that user over there'.
Real Talk
A foreign key is a column (or group of columns) in one table that references the primary key of another table. It enforces referential integrity — you cannot insert a foreign key value that does not exist in the referenced table, and deletion rules (CASCADE, RESTRICT, SET NULL) control what happens when the referenced row is deleted.
Show Me The Code
CREATE TABLE orders (
id SERIAL PRIMARY KEY,
user_id INT REFERENCES users(id) ON DELETE CASCADE,
total DECIMAL(10,2)
);
When You'll Hear This
"The user_id column is a foreign key referencing the users table." / "Foreign keys prevent orphaned records."
Related Terms
JOIN
JOIN combines rows from two tables based on a related column.
Junction Table
A junction table (also called a join table) is the middle table you create to represent a many-to-many relationship.
One-to-Many
One-to-Many means one row in Table A can relate to many rows in Table B. One user can have many orders. One post can have many comments.
Primary Key
A primary key is the unique ID that every row in a table must have. Like a social security number for your data — no two rows can have the same one.