Skip to content
Advertisement

Compound primary key issue with foreign key

I’m getting this error:

There are no primary or candidate keys in referenced table ‘User’ that match.

I checked for other similar questions but different answers didn’t help me.

Are my primary keys set wrong?
Must I reference only one primary key in ShoppingCart table ?

enter image description here

Thank you very much for all the users who answer me below.

Advertisement

Answer

As I have mentioned in the comments, the problem is that you are trying to create a FOREIGN KEY that references a PRIMARY KEY/UNIQUE CONSTRAINT in your table User which is made up of UserID and only UserID; no such constraint exists and as such the creation of the FOREIGN KEY fails.

To address this literally, you would need to add the EmailAddress column to the ShoppingCart table and the FOREIGN KEY‘s definition:

This, in truth, is a bad idea, as what do you think would happen if someone changed their email address? Well, let’s try. Firstly, let’s create some sample data:

And now Let’s say Jane has changed her Email address, so we try to UPDATE the table:

The INSERT statement conflicted with the FOREIGN KEY constraint “FK__ShoppingCart__36DDA17A”. The conflict occurred in database “Sandbox”, table “dbo.User”.

This is because the value of EmailAddress in the table ShoppingCart is still N'Jane@bloggs.com', so the value can’t be updated. Obviously, you can’t also UPDATE the value in dbo.ShopppingCart because you’ll get the same error:

The INSERT statement conflicted with the FOREIGN KEY constraint “FK__ShoppingCart__415B2FED”. The conflict occurred in database “Sandbox”, table “dbo.User”.

So what do you do instead? Well I assume that the email address is meant to be unique within the application, not by user. At the moment you could have 100 Users with a UserID of 1 and provided they all had different Email Addresses, they would be valid Primary Keys. Most likely what you really want, based on that you don’t want EmailAddress in the table ShoppingCard, is for UserID to be the Primary Key, and the Email Address to have a separate Unique Constraint. This gives you the following instead:

I also give your constraints explicit names, a habit you should really get into.

Now you can INSERT the sample data, and UPDATE the email address without issue:

And if you try to add another user with the same email address, you get an error:

Violation of UNIQUE KEY constraint ‘UQ_UserEmail’. Cannot insert duplicate key in object ‘dbo.User’. The duplicate key value is (Jane.Bloggs@email.com).

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement