Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Primary Key Duplicate Values

I have a table with 2 primary key columns : ID and StudentID.

ID column is set to isIdentity = Yes with auto increment.

I've tested it multiple times before, but for some reason this time, when I insert a duplicate value on StudentID, it does not throw the error but instead added it on to the database. 2 of the same values are displayed when I show the table data.

What can be the problem here?

like image 778
t_Consumer Avatar asked Mar 13 '23 14:03

t_Consumer


1 Answers

You have a compound primary key on ID and StudentID. That means you the combination of ID and StudentID together must be unique. Since ID is an identity column that combination of ID and StudentID will always be unique (because ID is already unique on its own).

You can change the primary key to be on ID only. Then you can add a unique index on StudentID. For example:

create unique index idx_studentID on yourTable(StudentID)

That will insure that the StudentID column, in fact, contains only unique values.

It seems like you may not actually need ID column, but that's a little wider discussion than your original question.

like image 190
user212514 Avatar answered Mar 15 '23 16:03

user212514