🔑 Data & Database Design · Data & Databases
Primary & Foreign Keys
Keys uniquely identify records and connect related records.
Stable identifiers keep relationships reliable.
OrderId identifies an order; CustomerId links it to a customer.
💡 A primary key is like a person's ID number — one unique label — and a foreign key is writing that number on a form to say who it belongs to.
💡 Why it matters
Keys are how a database knows one row from another and how it ties related rows together. Stable, unique keys keep joins correct and prevent accidental duplicates or orphaned records. Without them, relationships drift and data silently corrupts.
🛠️ How to achieve it
⚠️ Signs of trouble
- •Two rows describe the same thing with no way to tell them apart.
- •Child records point to parents that no longer exist (orphans).
- •Keys change over time, breaking older references.
- •Joins return wrong or duplicated results.
🎯 Quick check
Score: 0/3Three questions to test the idea.
1. What does a primary key do?
Answer: Uniquely identifies each row in a table
A primary key is the unique, stable label that tells one row apart from every other in the table.
2. Why avoid using an email address as a primary key?
Answer: It can change, breaking references
A primary key should be stable. Emails change, so a generated surrogate id is safer.
3. What is a foreign key used for?
Answer: Linking a row to a related row in another table
A foreign key holds another table's key, connecting the two rows, such as CustomerId on an Order.
