unique constraint to a foreign table

Viewed 71

I have two tables, experiment and sample. Samples must be unique within experiments of the same type, but can be shared between experiments that have a different type. I understand how I can add a unique constraint to the samples to make them always unique, but is it possible to create a unique constraint based on the information in the foreign table?

create table experiment (
id integer primary key,
name text,
type text
);

create table sample (
id integer primary key,
name text,
experiment_id integer,
);
alter table sample add constraint exp_fkey foreign key (experiment_id) references experiment(id);
1 Answers

You can create a (redundant) unique constraint on experiment (id, type), add type to sample, create a foreign key constraint from (experiment_id, type) to (id, type) and a unique constraint on sample.type.

Related