Predict the output
A psql script keeps going after an error, like app code that swallows the exception. What happens at the final SELECT?
CREATE TABLE users (email text PRIMARY KEY);
BEGIN;
INSERT INTO users VALUES ('a@x.io');
\set ON_ERROR_STOP 0
INSERT INTO users VALUES ('a@x.io'); -- duplicate: 23505
\set ON_ERROR_STOP 1
SELECT count(*) FROM users;Hint 1 of 1
What state is the transaction in after the 23505 error?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A It fails: current transaction is aborted (25P02)
Correct. The duplicate key error aborted the transaction; nothing else runs until ROLLBACK.
After any error inside a transaction, PostgreSQL rejects every later statement with 25P02 until ROLLBACK. A savepoint lets you roll back just the failed step and carry on.
Why not the others?
- B It prints 1. That's what you'd get with a savepoint and ROLLBACK TO before the SELECT.
- C It prints 2. The primary key rejects the duplicate.
- D It prints 0. No statement runs successfully after the error, including this one.