Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL require literal value in foreign column

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.

like image 788
kag0 Avatar asked Apr 28 '26 00:04

kag0


1 Answers

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)
);
like image 178
klin Avatar answered Apr 29 '26 20:04

klin