Primary key cannot be null, this is a rule. But why foreign key can? If it is also a primary key of another table.
Is it because it is not from the main table?
Primary key cannot be null, this is a rule. But why foreign key can? If it is also a primary key of another table.
Is it because it is not from the main table?
Pointing to Primary Keys
Foreign keys can point to primary keys of other/self tables. If it's null (or partially null), then it means it's doesn't have a referenced row.
Pointing to Unique Constraints
Foreign keys can also point to unique constraints as well; and these unique constraints can actually be nullable. Look at the example below:
create table person ( id int primary key not null, first_name varchar(20), last_name varchar(20), constraint uq1 unique (first_name, last_name) ); insert into person (id, first_name, last_name) values (1, 'Peter', 'Cantropus'); insert into person (id, first_name, last_name) values (2, 'Chad', 'Ensis'); insert into person (id, first_name, last_name) values (3, null, null); create table car ( brand varchar(30), owner_first_name varchar(20), owner_last_name varchar(20), constraint fkoc1 foreign key (owner_first_name, owner_last_name) references person(first_name, last_name) ); insert into car (brand, owner_first_name, owner_last_name) values ('Renault', 'Peter', 'Cantropus'); insert into car (brand, owner_first_name, owner_last_name) values ('Lada', null, null); insert into car (brand, owner_first_name, owner_last_name) values ('Sumi', 'Chad', null); select * from car; Result:
id first_name last_name -- ---------- --------- 1 Peter Cantropus 2 Chad Ensis 3 <null> <null> brand owner_first_name owner_last_name ------- ---------------- --------------- Renault Peter Cantropus -- not null: has a referenced row Lada <null> <null> -- null: not referencing Sumi Chad <null> -- partially null: not referencing As you see: