views:

120

answers:

2

Does a Foreign Key referencing a Primary Key need the NOT NULL constraint in a PostgreSQL database?
The database is highly normalized and will be very large. I do not wish to add extra constraints that will slow down the queries even more if said queries are unneeded.

A: 

A primary key must be unique, and ideally it should be picked by the database, to limit problems with concurrency, so, though it can be unique, for 1 record, every other record must have a value.

Otherwise, how will you know which row this foreign key relates to if there is more than one match?

So, as New in town mentioned, NULL should be valid, but for one record, as the uniqueness will be the larger issue.

EDIT: oops, misunderstood the question.

I have put null on foreign keys before, but if you have cascade delete for example then null won't work, unless you have the key in the primary table with a null value.

James Black
OP was asking about "not null" constraint on _FOREIGN_ key
ChssPly76
+3  A: 

If you want to be able to represent unknown in the FK column of that table, then make it nullable, if it has to have a value, make it Not Null.

You can have as many records as you want in the referencing table with null FK values. The unique constraint is on the rows in the referenced table (Where the PK is) not on the rows in the referencing table (where the FK is).

Charles Bretana
This is correct. To put it another way, it depends on whether you are modelling a 1:N relationship or a 0..1:N relationship. i.e. is the relationship optional?
Craig Fisher
1:1 relationship. The Table that I am working on is a bridge table.
WolfmanDragon
If it's 1:N Then the FK column SHOULD have the Not Null constraint on it.
Charles Bretana