I have three tables 1. Account 2. dept and 3. managers
In the managers table I need to add both account key and dept key as foreign key but one will null and other will have value, means if inserted account manager then dept key will null and account key will have value. how to add constraint in postgres
Question posted in PostgreSQL
The official documentation can be found here.
The official documentation can be found here.
2
Answers
Demo at db<>fiddle
One
null
, onenot null
If you always want exactly one of those foreign keys to be
null
and the othernot null
, you can use aXOR
. It won’t allow both to have a value, and it will also not allow a row where they are bothnull
:There’s a XOR
#
operator, but only for typebit
, so it’s not really worth all the casting:At most one
null
If you allow at most one to be
null
(one or both can benull
), you can count them:fiddle
Your description indicates yo are not looking for at most 1 null, but instead looking for exactly 1 null. You determine this with the num_nulls() function incorporated into a
check
constraint. So (see demo)