Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

insert or update on table violates foreign key constraint

Tags:

I have two tables: entitytype and project. Here are the create table statements:

Create table project ( 
pname varchar(20) not null, 
primary key(pname)
);

create table entitytype( 
entityname varchar(20) not null, 
toppos char(100), 
leftpos char(100), 
pname varchar(20) not null, 
primary key(entityname), 
foreign key(pname) references project(pname) on delete cascade on update cascade
);

When I try to insert any values into the entitytype table, I get the following error:

ERROR: insert or update on table "entitytype" violates foreign key constraint "entitytype_pname_fkey"
  Detail: Key (pname)=(494) is not present in table "project".

Can anyone shed some light on what I am doing wrong?

like image 446
suprasad Avatar asked Mar 15 '10 03:03

suprasad


People also ask

How do you fix the update statement conflicted with the foreign key constraint?

The way to fix this issue is to temporarily disable the FOREIGN KEY constraint - change the values and the set the FOREIGN KEY constraint again.

How do I fix foreign key constraint failure?

The error message itself showing there is a foreign key constraint error, which means you are deleting a parent table where the child table contains the Primary table identifier as a foreign key. To avoid this error, you need to delete child table records first and after that the parent table record.

What is foreign key violation?

Foreign key constraint violation occurred, dbname = database_name, table name = table_name, constraint name = constraint_name. 23000. Occurs when an insert or update on a foreign key table is performed without a matching value in the primary key table.

What is the foreign key constraint?

The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables. A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the PRIMARY KEY in another table.


2 Answers

The error message means you are attempting to add an entityType that does not have a corresponding Project entry. (I don't know your domain or what you are trying to achieve, but that schema design looks wrong to me...)

like image 191
Mitch Wheat Avatar answered Sep 30 '22 18:09

Mitch Wheat


Do you not have a record in table project with a pname of (in your example) 494?

The key relationship says no pname is allowed in the entity table unless it matches a pname in the project table.

like image 22
Larry Lustig Avatar answered Sep 30 '22 19:09

Larry Lustig