Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional PostgreSQL foreign key

Tags:

postgresql

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.

like image 780
trex005 Avatar asked Jun 05 '12 16:06

trex005


People also ask

Should I use foreign keys in Postgres?

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.

What is foreign key constraint in PostgreSQL?

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.

Can foreign key be null Postgres?

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.

Does foreign key have index Postgres?

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.


1 Answers

The short answer is no, Postgres does not have conditional foreign keys. Some options you might consider are:

  1. Just not have a FK constraint. Move this logic into the data access layer and live without the referential integrity.
  2. Allow 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.
  3. Add a dummy row in the referenced table for 0 and -1. Even if it just had bogus data, it would satisfy the FK constraint.

Hope this helps!

like image 199
Mike Christensen Avatar answered Oct 05 '22 16:10

Mike Christensen