In PostgreSQL, what’s the simplest way to enforce more than just existence on a foreign key?
For example, given the following tables:
create table "bar"
(
bar_id serial primary key,
status boolean not null
)
create table "foo"
(
foo_id serial primary key,
bar_id integer references "bar"
)
How could foo.bar_id be constrained to only rows of bar where status is true?
I can imagine how to do it with trigger functions, but it seems like I’d need several (insert, update on foo; update, delete on bar) so I’d like to know if there’s a more convenient method, perhaps purely using constraints.
You could make bar.status part of the primary key of the bar table. Then you put status on the foo table as part of the FK to bar. Also put a constraint that foo.status must equal true. It’s kind of a hack, but depending on the real world context, it might make sense.