What is primary and foreign key in database? Clarify it with examples.
5 marks
Question source
- Exam year
- 2079 BS / 2022 AD
- Level
- Gazetted Second Class, Assistant Level (Computer Operator – Prabidhik)
- Paper
- Paper II – Sewa Sambandhit Karya Gyan (Job Based Knowledge)
- Section
- Section B
Model answer
Keys are fields that uniquely identify records and link tables together. Without keys, a database cannot maintain accuracy or relationships.
Primary Key: A primary key is a field (or combination) that uniquely identifies each record in a table. It cannot be empty (NULL) and cannot repeat (UNIQUE).
Example — Student table:
| StudentID (PK) | Name | Class |
|---|---|---|
| 101 | Sita Sharma | 10 |
| 102 | Ram Thapa | 10 |
Here StudentID is primary key. No two students can have 101, and it can never be blank. Phone number is a bad primary key because it can change; ID is good because it is stable.
Foreign Key: A foreign key is a field in one (child) table that refers to the primary key of another (parent) table. It creates the relationship and enforces referential integrity.
Example — LibraryIssue table:
| IssueID | StudentID (FK) | Book |
|---|---|---|
| 1 | 101 | DBMS Book |
| 2 | 102 | Networking Book |
Here StudentID in LibraryIssue is a foreign key pointing to Student.StudentID. You cannot issue a book to StudentID 999 if 999 does not exist in Student table — Access/MySQL will reject it.
Together: Primary key = identity of its own table; Foreign key = link to another table’s identity. Example line for exam: Department.DeptID (PK) → Employee.DeptID (FK) makes one-to-many relationship.