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?
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.
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.
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.
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.
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...)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With