Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

postgres key is not present in table constraint

When trying to ALTER TABLE in Postgres 9.5 to create foreign key constraint: from product_template.product_brand_id to product_brand.id

ALTER TABLE public.product_template
    ADD CONSTRAINT product_template_product_brand_id_fkey 
    FOREIGN KEY (product_brand_id)
    REFERENCES public.product_brand (id) MATCH SIMPLE
    ON UPDATE NO ACTION
    ON DELETE SET NULL;

Returns error

ERROR:  insert or update on table "product_template" violates foreign key         constraint "product_template_product_brand_id_fkey"
DETAIL:  Key (product_brand_id)=(12) is not present in table "product_brand".
STATEMENT:  ALTER TABLE "product_template" ADD FOREIGN KEY ("product_brand_id") REFERENCES "product_brand" ON DELETE set null

Im confused why postgres is trying to find product_brand.product_brand_id, when the fkey is from product_template.product_brand_id to product_brand.id

Any ideas?

like image 496
Adam Sims Avatar asked Sep 19 '17 09:09

Adam Sims


People also ask

How do I add a primary key constraint to an existing table in PostgreSQL?

In PostgreSQL, a primary key is created using either a CREATE TABLE statement or an ALTER TABLE statement. You use the ALTER TABLE statement in PostgreSQL to add or drop a primary key.

How do I view constraints in PostgreSQL?

To find the name of a constraint in PostgreSQL, use the view pg_constraint in the pg_catalog schema. Join the view pg_catalog. pg_constraint with the view pg_class ( JOIN pg_class t ON t. oid = c.


1 Answers

The error message simply states that there is at least one row in the table product_template that contains the value 12 in the column product_brand_id

But there is no corresponding row in the table product_brand where the column id contains the value 12

Key (product_brand_id)=(12) relates the source column of the foreign key, not the target column.

like image 51
a_horse_with_no_name Avatar answered Sep 18 '22 20:09

a_horse_with_no_name