Is it possible in PostgreSQL to conditionally add a foreign key?
Something like:ALTER TABLE table1 ADD FOREIGN KEY (some_id) REFERENCES other_table WHERE some_id NOT IN (0,-1) AND some_id IS NOT NULL;
Specifically, my reference table has all positive integers (1+) but the table I need to add the foreign key to can contain zero (0), null and negative one (-1) instead, all meaning something different.
Notes:
I am fully aware that this is poor table design, but it was a clever trick built 10+ years ago when the features and resources we have available at this point did not exist. This system is running hundreds of retail stores so going back and changing the method at this point could take months which we don't have.
I can not use a trigger, this MUST be done with a foreign key.
Yes, you should. Foreign keys are just constrains which helps you to make relationships and be sure that you have correct information in your database. You should use them to prevent incorrect data entry from whatsoever. Save this answer.
A foreign key constraint specifies that the values in a column (or a group of columns) must match the values appearing in some row of another table. We say this maintains the referential integrity between two related tables.
A foreign key containing null values cannot match the values of a parent key, since a parent key by definition can have no null values. However, a null foreign key value is always valid, regardless of the value of any of its non-null parts.
PostgreSQL automatically creates indexes on primary keys and unique constraints, but not on the referencing side of foreign key relationships. When Pg creates an implicit index it will emit a NOTICE -level message that you can see in psql and/or the system logs, so you can see when it happens.
The short answer is no, Postgres does not have conditional foreign keys. Some options you might consider are:
NULL
in the column, which is perfectly valid even with a FK constraint. Then, use another column to store whatever the meaning of 0
and -1
is.0
and -1
. Even if it just had bogus data, it would satisfy the FK constraint.Hope this helps!
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