18

Will an AFTER INSERT trigger (function written in pl/PGsql) fire in a separate transaction than the original insert?

What I'm concerned about is if the trigger experiences an exception of some kind.
Can the trigger be rolled back without the original insert being affected?

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
bitcycle
  • 7,632
  • 16
  • 70
  • 121

2 Answers2

30

All PostgreSQL triggers execute in the same transaction as the transaction that has triggered them.

Edit: You can also use LISTEN + NOTIFY to send a message from your trigger to a code that executes outside of the transaction. In that case, the message will only be delivered at the point of a successful commit. Errors in listeners will not roll back the triggering transaction.

Jirka Hanika
  • 13,301
  • 3
  • 46
  • 75
10

Trigger procedures run in the same transaction as associated triggering events. But the effects of a trigger procedure can be rolled back separately.

You have to add exception handling to the after trigger.

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
Scott Marlowe
  • 8,490
  • 3
  • 23
  • 21