BolEnglishLearn · Play · Win
Login

🔑 Data & Database Design · Data & Databases

🔑

Primary & Foreign Keys

Data ConceptCoreModule 4

Keys uniquely identify records and connect related records.

Stable identifiers keep relationships reliable.

💡 In practice

OrderId identifies an order; CustomerId links it to a customer.

🖼️ CONCEPT PICTURE
A picture to help remember Primary & Foreign Keys
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.

💡 Learn🛠️ Apply🎯 Check

💡 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

1
Give every table a primary key
Choose one column (often a generated id) that uniquely identifies each row and never changes.
2
Prefer meaningless ids
Use a surrogate id rather than something like an email that might change later.
3
Link with foreign keys
Store the parent's key in the child row, such as CustomerId on an Order, to connect them.
4
Enforce the link in the database
Add a foreign-key constraint so you cannot save an Order pointing to a Customer that does not exist.

⚠️ 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.
⚠️ Common mistake: Using a changeable value like email or phone number as the primary key. Use a stable, generated id instead, and keep the changeable value as an ordinary attribute.

🎯 Quick check

Score: 0/3

Three questions to test the idea.

  1. 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. 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. 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.

🔑 Key terms

Primary key
The column that uniquely identifies each row.
Foreign key
A column holding another table's key to link the rows.
Surrogate key
A generated id with no business meaning.
Orphan record
A child row whose parent no longer exists.

✅ Review checklist

📊 Your progress

0%
Mark this topic learned to track it.
Saved in this browser.
🚀 Got it?
Mark it learned and move to the next topic.
Next topic →