Let’s break it down clearly:
Primary Key (PK):
- Definition: A primary key is a column (or a set of columns) in a table that uniquely identifies each row.
- Characteristics:
- Must be unique for every row.
- Cannot contain NULL values.
- A table can have only one primary key.
- Example:
| student_id | name | age |
|---|---|---|
| 1 | Alice | 20 |
| 2 | Bob | 21 |
Here, student_id is a primary key because it uniquely identifies each student.
Foreign Key (FK):
- Definition: A foreign key is a column (or set of columns) in a table that references the primary key in another table. It is used to maintain a relationship between two tables.
- Characteristics:
- Can have duplicate values.
- Can have NULL values (unless specified otherwise).
- Enforces referential integrity between tables.
- Example:
Table: Courses
| course_id | course_name |
|---|---|
| 101 | Math |
| 102 | Physics |
Table: Enrollments
| enrollment_id | student_id | course_id |
|---|---|---|
| 1 | 1 | 101 |
| 2 | 2 | 102 |
Here:
course_idin Enrollments is a foreign key referencingcourse_idin Courses.student_idin Enrollments could also be a foreign key referencingstudent_idin Students.
✅ Key difference:
- Primary key: uniquely identifies a row in its own table.
- Foreign key: creates a link to a primary key in another table.
