When create two tables using the following queries in PostgreSQL:
create table test_unique_pk (
id serial primary key,
value varchar not null
);
create table refer_unique_pk (
id integer,
value varchar,
foreign key (id, value) references test_unique_pk(id, value)
);
I got
there is no unique constraint matching given keys for referenced table "test_unique_pk".
If I modify the first table to
create table test_unique_pk (
id serial primary key,
value varchar not null,
unique(id, value)
);
It just works fine.
However since primary key is already unique, in my opinion, the composite (id, value)
should also be unique, since we can not construct two tuples with same id
, and thus we can not construct two equal tuples of (id, value)
.
If the above statement is correct, why PostgreSQL does not automatically add a unique constraint on composite references including primary key?