0

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

2
  • 2
    It fails immediately after the first erroneous query. Be careful if you use ORMs or connection pools; they may cache the queries. Commented Feb 23, 2022 at 3:10
  • Thanks! Guillaume. Also, thanks for the advice about the connection pools. Commented Feb 23, 2022 at 3:33

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.