Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The INSERT statement conflicted with the FOREIGN KEY constraint. The conflict occurred in database

I have been having this problem for a couple of hours now. In SQL Server, I ran this query :

INSERT INTO USERS_AVATAR(userId, avatId) VALUES ('1', '213');
INSERT INTO USERS_AVATAR(userId, avatId) VALUES ('2', '312');

but the message shows up saying :

Msg 547, Level 16, State 0, Line 1
The INSERT statement conflicted with the FOREIGN KEY constraint "FKUSERS_AVAT731248". The conflict occurred in database "gk314", table "gk314.USERS", column 'userId'.

Msg 547, Level 16, State 0, Line 2
The INSERT statement conflicted with the FOREIGN KEY constraint "FKUSERS_AVAT731248". The conflict occurred in database "gk314", table "gk314.USERS", column 'userId'.

Help please!

like image 775
problems Avatar asked Mar 24 '15 14:03

problems


People also ask

Why insert statement conflicted with the foreign key constraint?

You can get this error when you want to inset data into a table that has the Foreing Key. It means that there is no relevant record in the Primary table that Foreign Key is linked to. The record must first be added to the primary table.

What is a foreign key conflict?

FIX: A conflict with the foreign key constraint occurs when you update the case of the column values in the primary key table or you pad column values in the primary key table in SQL Server 2005. Skip to main content.


2 Answers

Before inserting userIds 1 and 2 into USERS_AVATAR, you must first insert them into table USERS. That is what the FOREIGN KEY constraint is requiring.

like image 198
Russ Avatar answered Oct 23 '22 08:10

Russ


Foreign key constraints are SQL's way of saying "this table expects data to exist in other tables". It allows you to reference other tables without the data having to exist twice or to be kept in sync.

In this case, there's a table for user data (USERS) and a table for avatar data (AVATARS), and the USERS_AVATAR table links the two together. You will need to add a user to the users table, then an avatar to the avatar table, then you can link the two together. It will look something like this:

INSERT INTO USERS (userId, email, password, status) VALUES (1, '[email protected]',' gk314', 'strong')
INSERT INTO AVATARS (avatId, name, ...) VALUES (1, 'Avatar1', ...)
INSERT INTO USERS_AVATAR (userId, avatId) VALUES (1, 1)

Original Answer:

This means that there's a table, gk314.USERS, that doesn't have a userId that matches the userId you're attempting to add to USERS_AVATAR. Check the USERS table and add users with userId 1 and 2, and then you should be able to add to the USERS_AVATAR table.

like image 32
Adam V Avatar answered Oct 23 '22 10:10

Adam V