Given:
- Table A with multiple rows and attributes: (A_attr1 (key) , A_attr2).
- Table B with attributes (B_attr1 (key) , A_attr1 (foreign key), B_attr2).
How do I insert some values in the table B only if the foreign key exists?
Given:
How do I insert some values in the table B only if the foreign key exists?
2
Answers
First, we need to consider the fact that the condition (existence of foreign key in table A) is fundamental, in fact, if we try to add values in Table_B with an A_attr1 that it doesn't exist in Table_A we get an error of this type:
This is a possible solution:
The result is the addition in B of all the tuples that are acceptable (that is the one with the existing foreign keys).
This post is an extension of the following question: PostgreSQL insert if foreign key exists
The solution is based on the comments on this post:
https://dba.stackexchange.com/questions/252875/how-to-make-on-conflict-work-for-compound-foreign-key-columns/252925#252925
In Postgres, we can use the
Where Exists
to implement your use case.Here is an example of using it.
This will insert only if the
"Foreign Value"
is present in Table_A.Hope this helps