I have the following tables:
CREATE TABLE `students` (
`student_id` int NOT NULL AUTO_INCREMENT,
`student_name` varchar(40) N
Let's say we stick to using the Auto Increment id
column as Primary Key. Now, we will also need to ensure that the data is consistent, i.e., there are no duplicate rows for a combination of (student_id, course_id)
values. So, we will need to either handle this in application code (do a select every time before insert/update), or we can fix this thing structurally by defining a Composite UNIQUE
constraint on (student_id, course_id)
.
Now, a Primary Key is basically a UNIQUE NOT NULL Key. If you look at your table definition, this newly defined UNIQUE constraint is basically a Primary Key only (because the fields are NOT NULL as well). So, in this particular case, you don't really need to use a Surrogate Primary key id
.
The difference in overheads during random DML (Insert/Update/Delete) will be minimal, as you would also have similar overheads when using a UNIQUE index only. So, you can rather define a Natural Primary Composite Key (student_id, course_id)
:
-- Drop the id column
ALTER TABLE students_courses DROP COLUMN id;
-- Add the composite Primary Key
ALTER TABLE students_courses ADD PRIMARY(student_id, course_id);
Above will also enforce the UNIQUE constraint on the combination of (student_id, course_id)
. Moreover, you will save 4 bytes per row (size of int
is 4 bytes). This will come handly when you would have large tables.
Now, while Joining from students
to students_courses
table, above Primary Key will be a sufficient index. However, if you need to Join from courses
to students_courses
table, you will need another key for this purpose. So, you can define one more key on course_id
as follows:
ALTER TABLE students_courses ADD INDEX (course_id);
Moreover, you should define Foreign Key constraints to ensure data integrity:
ALTER TABLE students_courses ADD FOREIGN KEY (student_id)
REFERENCES students(student_id);
ALTER TABLE students_courses ADD FOREIGN KEY (course_id)
REFERENCES courses(course_id);