MySQL + SQL · Lesson 17
Primary Key and Foreign Key
Primary Key
A primary key uniquely identifies each row in a table. It cannot be NULL and cannot repeat.
CREATE TABLE students (
roll_no INT PRIMARY KEY,
name VARCHAR(50)
);
Foreign Key
A foreign key is a column that refers to the primary key of another table, creating a link between them.
CREATE TABLE fees (
fee_id INT PRIMARY KEY,
roll_no INT,
amount INT,
FOREIGN KEY (roll_no) REFERENCES students(roll_no)
);fees.roll_no must match an existing students.roll_no.
Quick Difference
| Primary Key | Foreign Key |
|---|---|
| Identifies a row uniquely | Links to another table |
| Cannot be NULL | Can be NULL |
| One per table | Many allowed |
Summary
- Primary key = unique, not null, one per table.
- Foreign key = links tables, enforces referential integrity.