I
I
impressive172021-10-26 15:17:33
PostgreSQL
impressive17, 2021-10-26 15:17:33

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

2 answer(s)
M
Melkij, 2021-10-26
@impressive17

this happens in one transaction and apparently the data is not yet visible

The assumption is wrong.
Check carefully what you are doing. In particular, whether it is valid in the same transaction, whether the error speaks about this limitation or maybe about something else.

D
Dmitry Shitskov, 2021-10-26
@Zarom

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 question

Ask a Question

731 491 924 answers to any question