Unique relationship attribute for every pair of entities

All we need is an easy explanation of the problem, so here it is.

I have entities "Student" and "Course" and they are connected with relationship many-to-many called "Exam". The relationship "Exam" has an atribute "Grade". For this ER model, I have made a relational schema:

Student(StudentID, StudentName, DoB)
Course(CourseID, CourseName)
Exam(StudentID, CourseID, Grade)

Can someone explain how would you put in a relational schema the fact that a student can’t get multiple grades for a single course? For example, we can’t have records like (Student1, Course1, Grade1) and (Student1, Course1, Grade2).

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

In a relational database every table should have a Primary Key.

A Primary Key can be one column, like StudentId, or it can be a Compound Key, like (StudentID, CourseID), which is exactly what you should use for Exam.

Then Exam’s Primary Key guarantees that "a student can’t get multiple grades for a single course", because that would require multiple rows with the same (StudentID, CourseID) values.

Method 2

You would create a unique constraint on exam (StudentId, CourseId) this would usually be achieved with a unique index on that table that covered the two columns.

Here’s a quick demo in MySql

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply