Is it possible to require a specific literal value in a foreign key constraint?
For example
CREATE TABLE a (
id bigserial primary key,
b_id bigint not null,
foreign key (b_id, true) references b(id, flag)
);
CREATE TABLE b (
id bigserial primary key,
flag boolean
);
where we want to require that rows in a reference only rows in b with a flag set to true.
The syntax in the question is not valid (see CREATE TABLE). You can get the desired effect as follows:
CREATE TABLE b (
id bigserial,
flag boolean,
primary key(id, flag)
);
CREATE TABLE a (
id bigserial primary key,
b_id bigint not null,
flag boolean default true check (flag),
foreign key (b_id, flag) references b(id, flag)
);
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