I have such table:
--
-- PostgreSQL database dump
--
SET statement_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SET check_function_bodies = false;
SET client_min_messages = warning;
SET search_path = public, pg_catalog;
SET default_tablespace = '';
SET default_with_oids = false;
--
-- Name: forum; Type: TABLE; Schema: public; Owner: postgres; Tablespace:
--
CREATE TABLE forum (
forum_id integer DEFAULT nextval('seq_forum'::regclass) NOT NULL,
forum_name character varying NOT NULL,
group_id integer NOT NULL,
forum_parent integer DEFAULT (-1)
);
ALTER TABLE public.forum OWNER TO postgres;
--
-- Name: PK_forum; Type: CONSTRAINT; Schema: public; Owner: postgres; Tablespace:
--
ALTER TABLE ONLY forum
ADD CONSTRAINT "PK_forum" PRIMARY KEY (forum_id);
--
-- Name: FK_group; Type: FK CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY forum
ADD CONSTRAINT "FK_group" FOREIGN KEY (group_id) REFERENCES groups(group_id) ON UPDATE CASCADE ON DELETE CASCADE;
--
-- Name: FK_parent; Type: FK CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY forum
ADD CONSTRAINT "FK_parent" FOREIGN KEY (forum_parent) REFERENCES forum(forum_id);
--
-- PostgreSQL database dump complete
--
As you see above, this table has (at least should have …) a default value in column forum_parent. I want to insert some data to this table, I do it like this:
INSERT INTO forum (forum_name, group_id) VALUES('new forum', 1);
yup, I have a group with id = 1. But this code gives me:
PostgreSQL error: 23503 ERROR: insert or update on table "forum" violates foreign key constraint "FK_parent"
DETAIL: Key (forum_parent)=(-1) is not present in table "forum".
NOTICE: there is no transaction in progress
How to make it right?
Your
INSERTstatement is correct. When you don’t explicity declare the column name on yourINSERTstatement, the value that is inserted on the table is the default (in your case, it’s-1).But the problem lies on the referential constraint. The column
forum_parentof tableforumis dependent on the values of columnforum_idof the same table. As this DDL says,The
INSERTstatement failed during execution because the value-1is not present on columnforum_id.My suggestion is to change the default value from
-1toNULLThe difference between
NULLand-1is thatNULLis simply unknow. or the value does not exist while-1is an existing numeric value.