Ivan Sergio Borgonovo <mail(at)webthatworks(dot)it> writes:
> I'm not sure what's really happening but why apparently the delete
> statements get executed before the 2 inserts even if constraints are
> deferred?
You didn't mark the FK constraints as deferrable --- I'm pretty sure
the default is NOT DEFERRABLE.
> Why does it take so long?
Indexes on the FK columns would probably help.
regards, tom lane