Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL nullable Foreign Key

I'm creating a postgreSQL table that has a foreign key that references itself, so it's a structure which is similar to a tree:

CREATE TABLE Person(
    ID serial PRIMARY KEY,
    Description text,
    Name varchar(5),
    ParentID serial,
    FOREIGN KEY (ParentID) REFERENCES Person(ID)
    );

The problem is that ParentID is automatically set to NOT NULL and therefore there can be no root in this tree. How do I make it nullable?

like image 281
user3146897 Avatar asked Dec 30 '13 16:12

user3146897


People also ask

What happens when a foreign key contains a null value?

Once at least one of the referencing columns of the foreign key contains a NULL value, there is no link to the referenced table. This is because a NULL is not comparable with another NULL value, as per 3VL. This also means that defined cascading actions (such as ... DO DELETE, ...

How to avoid the FOREIGN KEY constraint when referencing rows?

If you don't want referencing rows to be able to avoid satisfying the foreign key constraint, declare the referencing column (s) as NOT NULL. A foreign key must reference columns that either are a primary key or form a unique constraint.

What is the NULL constraint in PostgreSQL?

The NULL constraint is not present in the SQL standard and should not be used in portable applications. (It was only added to PostgreSQL to be compatible with some other database systems.) Some users, however, like it because it makes it easy to toggle the constraint in a script file.

Is it possible to set the FK Field to null in pgSQL?

The FK field would then be NULL, if the database let me, of course. Unfortunately, I get an error when trying to set fk_quotation_receipt_id to NULL in an INSERT statement because of a violated foreign key constraint. When designing these tables I was still using PgSQL 8.2, which allowed NULL values.


1 Answers

You probably want to change the type of your ParentID to an integer, which is the underlying type of serial.

CREATE TABLE Person(
    ID serial PRIMARY KEY,
    Description text,
    Name varchar(5),
    ParentID integer,
    FOREIGN KEY (ParentID) REFERENCES Person(ID)
);

The documentation for the integer and serial data type is available here: http://www.postgresql.org/docs/current/static/datatype-numeric.html

like image 90
Erik Näslund Avatar answered Oct 20 '22 05:10

Erik Näslund