1

I want to run a script inside a transaction in PostgreSQL. So I surround the SQL code with begin and commit statements. But I want to rollback on error. I don't see how to do that.

BEGIN;
UPDATE public.tablename
SET blah = 'xxx'
WHERE thing= '123';

COMMIT;

Erwin Brandstetter
  • 185,527
  • 28
  • 463
  • 633

2 Answers2

1

I found the answer. The rollback will happen when an error occurs without me doing anything.

armitage
  • 1,429
  • 2
  • 14
  • 20
0

You set a savepoint and after the comand a Rollback

CREATE tABLE tablename (blah varchar(3), thing varchar(3))
BEGIN;
SAVEPOINT my_savepoint;
   UPDATE tablename
   SET blah = 'xxx'
   WHERE thing= '123';
ROLLBACK TO my_savepoint;
COMMIT;

db<>fiddle here

nbk
  • 8,699
  • 6
  • 14
  • 27