WHY pick just one: a table needs a single, stable handle for relationships and indexing. Other
candidate keys become alternate keys (still unique, enforced with UNIQUE, but not "the" key).
Recall Feynman: explain to a 12-year-old (click to reveal)
Imagine a classroom. Every kid needs a way to be picked out from everyone else.
Super key = any description that points to exactly one kid — even a wordy one like "the kid
with roll 7 wearing red". Extra words are fine as long as it's unique.
Candidate key = the shortest such descriptions that still work, like just "roll 7".
Primary key = the one we officially write on everyone's name tag — say the roll number.
Foreign key = when the library wants to note who borrowed a book, it writes the kid's roll
number, borrowing the classroom's name-tag system.
Natural name tag = something true about them (their email). Surrogate = a random ticket
number we hand out that means nothing but never changes.
Dekho, ek database table basically rows ka ek set hota hai, aur set mein duplicate nahi chalte.
Toh humein har row ko alag se pehchaanne ka tarika chahiye — yahi cheez key kehlaati hai.
Sabse general idea hai super key: koi bhi columns ka group jiski value har row mein unique ho.
Usme extra faltu column bhi ho sakte hain. Jab tum usme se faltu columns hata ke sabse chhota
unique set bana lo, woh ban jaata hai candidate key (minimal). In candidate keys mein se jo ek
official identifier choose karte ho — wahi primary key hai, jo hamesha unique aur NOT NULL hoti hai.
Foreign key ka kaam hai do tables ko jodna. Maan lo Student table mein roll_no primary key hai,
aur Enrolment table mein bhi roll_no likha hai jo Student ko point karta hai — yeh foreign key hai.
Important baat: foreign key column mein values repeat ho sakti hain (ek student ke multiple
enrolments), lekin jis cheez ko woh point kar raha hai (PK) woh unique hona zaroori hai. Isse
referential integrity milti hai — tum kisi aise student ko reference nahi kar sakte jo exist hi
nahi karta.
Natural vs surrogate: natural key matlab real-world data jaise email ya ISBN — jiska meaning hota
hai. Problem yeh ki email change ho sakta hai, ya NULL ho sakta hai. Isiliye log surrogate key
use karte hain — ek auto-increment id ya UUID jiska koi business meaning nahi, par woh stable rehti
hai aur kabhi change nahi karni padti. Best practice: surrogate id ko PK banao, par natural data
(email) pe UNIQUE constraint zaroor lagao taaki duplicate real entities na ghusein. Yaad rakho ladder:
Super → Candidate → Primary (chhoti hoti jaati hai), aur Foreign = doosri table ka reference.