Can foreign key references contain NULL values in

2020-03-01 06:10发布

问题:

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?

回答1:

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).


回答2:

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.