In short
Two customers can both be called Rahul Sharma from Delhi. Keys are how a database tells rows apart, and how it links an order back to exactly the right customer.
A primary key uniquely identifies each row in a table, and a foreign key in another table points to it, which is how relational databases link related data.

Think of it like this
Hostel rooms and mess slips
Every hostel room has a unique number, like A-204. That is the primary key: no two rooms share it. A mess slip says "Room A-204" to show who ate. That reference is a foreign key, and the warden won't accept a slip for a room that doesn't exist.
Watch it happen
The database guards the link
INSERT order for customer 7
1/5The app tries to save an order with customer_id = 7.
The big ideas
What you need to know
Primary key is unique
Each table gets one primary key. Its value is unique and never NULL, so it points to exactly one row.
Foreign key points to a parent
orders.customer_id refers to customers.customer_id. That shared value is how two tables relate.
Integrity is enforced
With a foreign key, the database blocks orders for customers that don't exist, so bad links never get in.
Prefer simple surrogate IDs
Phone numbers and emails change. An auto-generated number that means nothing makes a stable key.
See it in code
Walk through the code
1CREATE TABLE customers (2 customer_id INTEGER PRIMARY KEY,3 name TEXT NOT NULL,4 city TEXT5);6 7CREATE TABLE orders (8 order_id INTEGER PRIMARY KEY,9 customer_id INTEGER NOT NULL REFERENCES customers (customer_id),10 amount NUMERIC(10, 2)11);12 13INSERT INTO customers VALUES (7, 'Meera Nair', 'Kochi');14INSERT INTO orders VALUES (1, 7, 1499.00); -- works15INSERT INTO orders VALUES (2, 99, 799.00); -- fails: no customer 991/4customers is the parent. customer_id is its primary key.
The parent table must exist first. MySQL needs the InnoDB engine (the default) for foreign keys to be enforced, and prefers the FOREIGN KEY (...) REFERENCES ... form.
Save yourself the pain
Common mistakes
Oops
Using a customer's name or phone number as the primary key.
Do this instead
Names repeat and phones change. Use a generated ID, and add a UNIQUE constraint on phone if needed.
Oops
Linking tables by a matching column but never declaring a foreign key.
Do this instead
Add REFERENCES so the database rejects orphan rows instead of you finding them months later.
Your mission
Trace the links
Quick check
Which statement about a primary key is true?
Go deeper
- 1Add an id primary key to every table you create.
- 2Add a foreign key from orders to customers and try inserting an order for a customer who doesn't exist.
- 3Learn what ON DELETE CASCADE does and when it is dangerous.
More topics at this stop
Stuck on this topic? Ask an Insider
Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.