Jason Mell
Jason Mell

Reputation: 103

PostgreSQL Foreign Key with a condition

Using postgres sql, is there a way to set up a condition on foreign key where it's limited to to another table like a normal foreign key constraint, but also allows the value of 0 to exist without it being in the other table. For example:

table_a:
  id

table_b:
  id
  foreign_key_on_table_a_id

table_a would have a list of things, and table_b relates to table_a, but has the foreign key constraint. I would also like it to allow for a value of 0 even though there is no id of 0 in table_a.

Is this the right constraint to use? Is there another/better way of doing this without adding the value into table_a?

Upvotes: 1

Views: 2531

Answers (1)

mu is too short
mu is too short

Reputation: 434665

I'd change foreign_key_on_table_a_id to allow NULL values. Then use an FK as usual and put NULLs in there instead of zero. You can have a NULL in a column that references another table.

Alternatively, you could write a function that returns true if a value is in the other table and false otherwise and then add a CHECK constraint:

CHECK (your_column = 0 or the_function(your_column))

You won't get any of the usual cascade behavior for FKs though and this CHECK is a massive kludge.

Upvotes: 2

Related Questions