Jarree Arham Shahid Jarree Arham Shahid - 5 months ago 26
SQL Question

Make sure that atleast one foreign key is not null

I have a situation in which I have to make sure that one of my foreign keys are not null. There are 2 foreign keys being referenced in my table and I want to make sure that both are not null. There should be a value in at least one of them.

How can I apply a check statement to this?

I am using Postgresql.



Use check constraint, e.g.:

create table tab3 (
    id int primary key, 
    id1 int references tab1,
    id2 int references tab2,
    check (id1 is not null or id2 is not null)