Transactions Basics
9 examples to get you started with PostgreSQL transactions - 6 basic and 3 intermediate.
Search across all documentation pages
9 examples to get you started with PostgreSQL transactions - 6 basic and 3 intermediate.
Sample tables with foreign keys to observe rollback behavior.
# Local dev with Docker (PostgreSQL 18)
docker run -d --name pg18 -e POSTGRES_PASSWORD=dev -p 5432:5432 postgres:18
psql postgres://postgres:dev@localhost:5432/postgresBEGIN starts a block; COMMIT makes it durable.
BEGIN;
UPDATE app.accounts SET name = 'Acme Corp' WHERE id = 1;
COMMIT;ROLLBACK discards uncommitted work.
BEGIN;
UPDATE app.accounts SET name = 'Bad' WHERE id = 1;
ROLLBACK;
SELECT name FROM app.accounts WHERE id = 1;Nested rollback point.
BEGIN;
INSERT INTO app.accounts (name) VALUES ('Temp');
SAVEPOINT sp1;
UPDATE app.accounts SET name = 'Oops' WHERE name = 'Temp';
ROLLBACK TO sp1;
COMMIT;Single statement failure in autocommit aborts that statement only.
INSERT INTO app.accounts (id, name) VALUES (1, 'dup'); -- fails if id=1 existsSame session sees committed changes.
BEGIN;
INSERT INTO app.accounts (name) VALUES ('NewCo') RETURNING id;
-- same TX sees row
COMMIT;Check FK at commit time.
SET CONSTRAINTS ALL DEFERRED;
BEGIN;
-- reorder inserts within TX
COMMIT;Pseudo-code shape for services.
-- SQL session
BEGIN;
-- business statements
COMMIT;Prepared transactions for external coordinators.
PREPARE TRANSACTION 'txn_abc';
-- later: COMMIT PREPARED 'txn_abc';pg_stat_activity state.
SELECT pid, xact_start, state, query
FROM pg_stat_activity
WHERE state IN ('idle in transaction','active');Stack versions: This page was written for PostgreSQL 18.4 (stable 18, maintenance 17), pgvector 0.8+, PgBouncer 1.x, Patroni 3.x, and PostGIS 3.5+.
Reviewed by Chris St. John·Last updated Jul 16, 2026