I was wondering at what point a transaction actually fails in Postgres. By this I mean stop working, and return an error. Is it after the first failed query? Does it try all queries and then return failure? Hopefully it fails fast on first failed query, but I don’t know for sure.
For instance, if I have a transaction with 5 insert statements, but insert 2 fails, does it stop right then and return an error?
Thanks
Advertisement
Answer
If you have a transaction spanning multiple statements, and one of these statements causes an error, the whole transaction is aborted and can only be rolled back. Here is a psql
session that exhibits that behavior:
test=> BEGIN; BEGIN test=*> SELECT 42; ?column? ══════════ 42 (1 row) test=*> SELECT 1 / 0; ERROR: division by zero test=!> SELECT 42; ERROR: current transaction is aborted, commands ignored until end of transaction block test=!> COMMIT; ROLLBACK