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?
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.
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.
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).
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_table
s you describe are actually very different, if you consider what you are trying to achieve.
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