Skip to content

Instantly share code, notes, and snippets.

@cabecada
Created January 7, 2026 09:36
Show Gist options
  • Select an option

  • Save cabecada/4dfb39be6ca8f820a0a44dfa76e58876 to your computer and use it in GitHub Desktop.

Select an option

Save cabecada/4dfb39be6ca8f820a0a44dfa76e58876 to your computer and use it in GitHub Desktop.
postgresql subtransactions error exception catch
Frank Pachot
https://lnkd.in/dMPzDBWK
Laurenz Albe from cybertec-postgresql
https://lnkd.in/drp932PZ
Nikolay Samokhvalov from postgres ai
https://lnkd.in/dHmtVdT7
postgres=# do $BODY$
begin
insert into demo (id) values(1);
commit;
insert into demo (id) values(1);
exception
when unique_violation then
raise notice 'ignoring duplicate';
end;
$BODY$;
ERROR: cannot commit while a subtransaction is active
CONTEXT: PL/pgSQL function inline_code_block line 4 at COMMIT
postgres=# do $BODY$
begin
insert into demo (id) values(1);
commit;
insert into demo (id) values(1);
exception
when others then
raise notice 'ignoring duplicate';
end;
$BODY$;
NOTICE: ignoring duplicate
DO
The reason you don't see the "subtransaction is active" error message is that your WHEN OTHERS block caught that exact error.
In PostgreSQL, a BEGIN ... EXCEPTION block creates an implicit subtransaction. When you try to COMMIT inside that block, PostgreSQL triggers a specific error: invalid_transaction_termination (SQLSTATE 2D000). Because your code uses WHEN OTHERS, it intercepts that error before it reaches your console, prints 'error', and exits gracefully.
postgres=# do $BODY$
begin
insert into demo (id) values(1);
commit;
insert into demo (id) values(1);
exception
when others then
RAISE NOTICE 'Error Message: %', SQLERRM;
end;
$BODY$;
NOTICE: Error Message: cannot commit while a subtransaction is active
DO
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment