⬅ Previous Topic
ER Diagrams and Schema DesignNext Topic ⮕
Foreign Keys and Relationships⬅ Previous Topic
ER Diagrams and Schema DesignNext Topic ⮕
Foreign Keys and RelationshipsEvery student in a school is unique — but not in the same way. Roll numbers are unique and mandatory. Aadhaar numbers are also unique but may not be available at admission time. In database terms, these differences are captured using Primary Keys and Unique Keys.
A Primary Key uniquely identifies each record in a table. It has two strict rules:
A Unique Key also enforces uniqueness, but:
CREATE TABLE students (
roll_no INT PRIMARY KEY,
name VARCHAR(50),
aadhaar_number BIGINT UNIQUE,
email VARCHAR(100) UNIQUE
);
roll_no
is the Primary Key — required and must be uniqueaadhaar_number
and email
are Unique Keys — can be NULL if not provided-- Valid
INSERT INTO students VALUES (1, 'Aarav Sharma', 123456789012, 'aarav@example.com');
-- Valid even if Aadhaar is missing
INSERT INTO students VALUES (2, 'Diya Iyer', NULL, 'diya@example.com');
-- Invalid: duplicate roll_no (Primary Key violation)
INSERT INTO students VALUES (1, 'Mehul Agarwal', 222233334444, 'mehul@example.com');
-- Invalid: duplicate email (Unique Key violation)
INSERT INTO students VALUES (3, 'Sneha Patil', NULL, 'aarav@example.com');
Aspect | Primary Key | Unique Key |
---|---|---|
Uniqueness | Enforced | Enforced |
NULL allowed? | No | Yes (once or more) |
Count per table | Only one | Multiple allowed |
Default index | Clustered index (in some DBs) | Non-clustered index |
Use case | Main identifier | Alternative identifiers (like Aadhaar, email) |
roll_no
– Primary Key (must exist for every student)aadhaar_number
– Unique Key (may be missing initially)email
– Unique Key (optional but must not repeat)Primary Key is your table’s identity — strict, non-negotiable, and singular. Unique Keys are like extra ID cards — optional but must be individually unique. Together, they shape a table’s reliability and help enforce real-world rules in digital data.
Next: Foreign Key Constraints — how to build relationships across tables and enforce data consistency.
CREATE TABLE students (
roll_no INT PRIMARY KEY,
email VARCHAR(100) UNIQUE,
name VARCHAR(100)
);
⬅ Previous Topic
ER Diagrams and Schema DesignNext Topic ⮕
Foreign Keys and RelationshipsYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.