Skip to main content

Composite & Alternate Keys πŸ—οΈπŸ—οΈ

Mentor's Note: In simple tables, one ID is enough. But in the real world, identity can be complex. Sometimes it takes two people to open a safeβ€”and sometimes it takes two columns to identify a row. πŸ’‘


🌟 The Scenario: The Hotel Room πŸ¨β€‹

Imagine you are managing a massive hotel.

  1. Composite Key: A 'Room Number' isn't enough because there is a Room 101 on Floor 1 and a Room 101 on Floor 2. To find the exact room, you need (Floor + Room).
  2. Alternate Key: Every guest has a 'Guest ID' (Primary Key), but they also have a 'Passport Number'. The Passport Number could have been the ID, but we chose Guest ID instead.

πŸ’» 1. The Composite Key​

A primary key that consists of two or more columns.

Syntax​

CREATE TABLE enrollments (
student_id INT,
course_id INT,
enroll_date DATE,
-- βš“ Combined Anchor
PRIMARY KEY (student_id, course_id)
);

Why use it? To prevent a student from enrolling in the same course twice.


πŸ“– 2. Candidate & Alternate Keys​

Candidate Key​

Any column (or set of columns) that could be a Primary Key (it's unique and not null).

  • Examples: Email, Aadhar Card No, Passport No.

Alternate Key​

A Candidate Key that was not chosen to be the Primary Key. We still want to keep it unique!

CREATE TABLE employees (
emp_id INT PRIMARY KEY, -- βš“ Chosen PK
email VARCHAR(100) UNIQUE, -- ✨ Alternate Key
aadhaar_no VARCHAR(12) UNIQUE -- ✨ Alternate Key
);

🎨 Visual Logic: The Key Hierarchy​


πŸ“Š Summary of Advanced Terms​

TermMeaningAnalogy
Super KeyAny set of columns that identifies a row.Any combo including your Roll No.
Candidate KeyMinimal set of unique columns.Your Roll No OR your Email.
Composite KeyPK made of 2+ columns.(Floor + Room Number).
Surrogate KeyAn artificial ID (1, 2, 3...).A token number at a bank.

πŸ“ˆ Learning Path​

πŸ“ Visit Us

🏫 VD Computer Tuition Surat

VD Computer Tuition
πŸ“ Address
2/66 Faram Street, Rustompura
Surat – 395002, Gujarat, India
πŸ“ž Phone / WhatsApp
+91 84604 41384
🌐 Website

Computer Classes & Tuition β€” Areas We Serve in Surat

Adajanβ€’Althanβ€’Amroliβ€’Athwaβ€’Athwalinesβ€’Bhagalβ€’Bhatarβ€’Bhestanβ€’Canal Roadβ€’Chowkβ€’Citylightβ€’Dumasβ€’Gaurav Pathβ€’Ghod Dod Roadβ€’Haziraβ€’Jahangirpuraβ€’Kamrejβ€’Kapodraβ€’Katargamβ€’Limbayatβ€’Magdallaβ€’Majura Gateβ€’Mota Varachhaβ€’Nanpuraβ€’New Citylightβ€’Olpadβ€’Palβ€’Pandesaraβ€’Parle Pointβ€’Piplodβ€’Punaβ€’Randerβ€’Ring Roadβ€’Rustampuraβ€’Sachinβ€’Salabatpuraβ€’Sarthanaβ€’Sosyo Circleβ€’Udhnaβ€’Varachhaβ€’Ved Roadβ€’Vesuβ€’VIP Road
πŸ“ž Call SirπŸ’¬ WhatsApp Sir