Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can foreign key references contain NULL values in PostgreSQL?

As an example

create table indexing_table
(
  id SERIAL PRIMARY KEY,
  created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
);

Is there a difference between the following tables?

Table 1:

create table referencing_table
(
  indexing_table_id INTEGER references indexing_table
);

Table 2:

create table referencing_table
(
  indexing_table_id INTEGER references indexing_table NOT NULL
);

Alternatively, in the case of Table 1, where there is no NOT NULL constraint, are we allowed to insert records containing NULL values?

like image 301
Alex Avatar asked Jan 29 '15 02:01

Alex


People also ask

Can a foreign key reference be null?

A table can have many foreign keys. A foreign key is nullable if any part is nullable. A foreign key value is null if any part is null.

Why are foreign key allowed to have null values?

Yes, foreign keys are allowed to have NULL values, Foreign keys simply require that the value in that field must exist first in a different table (the parent table). However, Null by definition is not a value. Null signifies that we do not yet know what the value is.


2 Answers

For table 1, this INSERT statement will succeed. If you run it 100 times, it will succeed 100 times.

insert into referencing_table values (null); 

The same INSERT statement will fail on table 2.

 ERROR:  null value in column "indexing_table_id" violates not-null constraint DETAIL:  Failing row contains (null). 
like image 67
Mike Sherrill 'Cat Recall' Avatar answered Oct 08 '22 10:10

Mike Sherrill 'Cat Recall'


Sometimes you want a foreign keyed column to be nullable because it is not required (just as not every citizen in a citizens table went to a university, so a university_id column can be null). In other cases, the column should not be null, just as every student lshould be associated with a university_id.

Therefore, the two referencing_tables you describe are actually very different, if you consider what you are trying to achieve.

like image 41
richyen Avatar answered Oct 08 '22 12:10

richyen