8.1.3 Relationships and Referential Integrity
A relationship describes how records in tables are associated. A foreign key stores a reference to a primary key. Referential integrity prevents references to records that do not exist.
By the end of this page, you should be able to:
- define and use the key terms accurately;
- explain how the idea works using a new example;
- apply the idea to a database design or SQL task.
1. Read relationship counts from the scenario
A one-to-one relationship allows one record at each end to match one record at the other end. In a one-to-many relationship, one record can match several records. Optionality tells whether zero related records are allowed. “A room may have no booking” is optional on the booking side.
2. Resolve many-to-many relationships
In a many-to-many relationship, each item on either side can be linked to several items on the other side. A single field cannot safely hold a list of all links. Add a linking table. For example, WorkshopRegistration can store one ParticipantID and one WorkshopID per registration.
3. Use a foreign key to connect records
A foreign key is a field in one table whose values refer to a primary key in another table. If WorkshopRegistration.ParticipantID refers to Participant.ParticipantID, every registration can be linked to a real participant.
4. Enforce referential integrity
Referential integrity means that each non-NULL foreign-key value must match a value in the referenced primary-key field. If there is no Participant with ID 74, a registration must not refer to ParticipantID 74. The DBMS can reject the invalid insert or update.
Worked example
Participant has IDs 41 and 52. A registration with ParticipantID 52 is valid. A registration with ParticipantID 74 is invalid until that participant record exists. If the relationship is optional, an empty (NULL) foreign key may be allowed.
Common mistake to avoid
“The tables are linked” is not enough. Explain which field is the foreign key, which field is the referenced primary key, and what values are checked.
Interactive check
Choose an answer, read the explanation, and continue to the next example.
Independent practice
Try this original question before opening the suggested response.
A community centre offers many courses. Each learner can join several courses, and each course can have many learners. Name the relationship, suggest a linking table and explain one integrity rule. (4)
Suggested response
Learner and Course have a many-to-many relationship. Use CourseJoin(LearnerID, CourseID) as a linking table. LearnerID refers to Learner.LearnerID and CourseID refers to Course.CourseID. Each non-NULL foreign-key value must match an existing primary-key value.
Answering clearly
Use the technical term, state what it does, and connect your explanation to the details in the question.