Answer the question
In order to leave comments, you need to log in
How to insert fk on a record added in the same transaction?
I am adding a record to table 1 in one transaction, getting the id of the inserted record (using 'RETURNING id') and trying to insert this id into table 2, as a foreign key in table 1.
I get an error that id is not found in table 1 (this happens in one transaction and apparently the data is not yet visible)
What is the correct way to act in such a situation or is the only way to make adding fk to Table 2 in a separate transaction?
Answer the question
In order to leave comments, you need to log in
this happens in one transaction and apparently the data is not yet visible
You need to specify for your FK that the constraint check can be deferred (DEFERRABLE), but not by default (INITIALLY IMMEDIATE). You need to specify either when creating a table, or execute ALTER CONSTRAINT
DEFERRABLE INITIALLY IMMEDIATE
After that, at the beginning of the transaction, you can declare the check of your FK as deferred
SET CONSTRAINTS some_fk DEFERRED;
PS Well, or execute your queries in different transactions, if it is permissible
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question