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?
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, ...
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With