To create a table, I use:
CREATE TABLE category ( cat_id serial NOT NULL, cat_name character varying NOT NULL, parent_id integer NOT NULL, CONSTRAINT cat_id PRIMARY KEY (cat_id) ) WITH ( OIDS=FALSE ); ALTER TABLE category OWNER TO pgsql;
parent_id is the identifier of another category. Now I have a problem: how to cascade a delete record with its children? I need to set parent_id as a foreign key for cat_id. I try this:
ALTER TABLE category ADD CONSTRAINT cat_cat_id_fkey FOREIGN KEY (parent_id) REFERENCES category (cat_id) MATCH SIMPLE ON UPDATE CASCADE ON DELETE CASCADE
But he falls from:
ERROR: insert or update on table "category" violates foreign key constraint "cat_cat_id_fkey" DETAIL: Key (parent_id)=(0) is not present in table "category".
source share