Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ERROR: null value in column "column_name" of relation "relation_name" violates not-null constraint

I have this table:

DROP TABLE IF EXISTS mission CASCADE;

CREATE TABLE mission 
(
    id_mission SERIAL PRIMARY KEY,
    task_description VARCHAR(255) NOT NULL
);

And a mission can depend of another to be unlocked. So I have the next reflexive table:

DROP TABLE IF EXISTS depends CASCADE;

CREATE TABLE depends 
(
    id_mission_1 INTEGER,
    id_mission_2 INTEGER, -- it can be null (optional)
    FOREIGN KEY (id_mission_1) REFERENCES mission (id_mission),
    FOREIGN KEY (id_mission_2) REFERENCES mission (id_mission),
    PRIMARY KEY (id_mission_1, id_mission_2)
);

I’m importing the data from another table like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

INSERT INTO depends(id_mission_1, id_mission_2)
    SELECT quest_id, quest_depends
    FROM player_quest;

The player_quest table looks like this:

enter image description here

We can see that not all the missions depend on one another, so there can be null values.

I’m getting the following error:

ERROR: null value in column "id_mission_2" of relation "depends" violates not-null constraint

Failing row contains (14, null).

How can I fix this?

Database: PostgreSQL

>Solution :

Primary key columns can never be null. Use a UNIQUE constraint instead:

CREATE TABLE depends 
(
    id_mission_1 INTEGER,
    id_mission_2 INTEGER, -- it can be null (optional)
    FOREIGN KEY (id_mission_1) REFERENCES mission (id_mission),
    FOREIGN KEY (id_mission_2) REFERENCES mission (id_mission),
    UNIQUE (id_mission_1, id_mission_2)
);

Note that several (14, null) rows can be inserted!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading