Transactions

Updated · 9 min read
mediumPostgreSQL 18sqltransactionscommitrollbacksavepointacidinterview

A transaction groups several statements into one unit: either all of their changes are saved, or none are. Enrolling Advitha in JavaScript Basics and recording her first payment are two INSERTs into two tables. If the enrollment is saved and the payment fails, the Fee Tracker shows a student enrolled in a course she never paid for; if the payment is saved without the enrollment, the foreign key refuses it. A transaction makes the pair all-or-nothing. This lesson covers BEGIN, COMMIT and ROLLBACK, what happens when a statement fails inside a transaction, savepoints, and what the database does so a committed change survives even a power cut.

In One Minute

  • BEGIN starts a transaction; COMMIT saves all its changes; ROLLBACK throws them all away.
  • Outside a transaction, each statement commits on its own (autocommit).
  • Inside a transaction, your changes are visible to you at once, and to others only after COMMIT.
  • After an error, PostgreSQL refuses further statements until you ROLLBACK (or ROLLBACK TO a savepoint).
  • SAVEPOINT name marks a point you can roll back to without losing the whole transaction.

BEGIN, COMMIT and ROLLBACK

SQL
BEGIN;
  statement;
  statement;
COMMIT;      -- or ROLLBACK;

Enroll Advitha (102) in JavaScript Basics (course 5) and record her payment, together:

SQL▶ Try it
BEGIN;
 
INSERT INTO enrollments VALUES (102, 5, '2026-01-05', 'active');
 
INSERT INTO payments (student_id, course_id, amount_usd, due_on, paid_on, method)
VALUES (102, 5, 225.00, '2026-01-05', '2026-01-05', 'card');
 
COMMIT;
 
SELECT student_id, course_id, amount_usd FROM payments WHERE student_id = 102;
Output
BEGIN
 
INSERT 0 1
 
INSERT 0 1
 
COMMIT
 
 student_id | course_id | amount_usd
------------+-----------+------------
        102 |         5 |     225.00
(1 row)

Both inserts were saved at the COMMIT. Now the same two statements, ending in ROLLBACK:

SQL▶ Try it
BEGIN;
 
INSERT INTO enrollments VALUES (102, 5, '2026-01-05', 'active');
 
INSERT INTO payments (student_id, course_id, amount_usd, due_on, paid_on, method)
VALUES (102, 5, 225.00, '2026-01-05', '2026-01-05', 'card');
 
ROLLBACK;
 
SELECT count(*) AS advitha_payments FROM payments WHERE student_id = 102;
SELECT count(*) AS javascript_enrollments FROM enrollments WHERE student_id = 102 AND course_id = 5;
Output
BEGIN
 
INSERT 0 1
 
INSERT 0 1
 
ROLLBACK
 
 advitha_payments
------------------
                0
(1 row)
 
 javascript_enrollments
------------------------
                      0
(1 row)

Both inserts ran, and then both were undone, as if they'd never happened. BEGIN TRANSACTION and START TRANSACTION mean the same as BEGIN.

COMMIT saves the enrollment and the payment together; ROLLBACK discards both

Autocommit: One Statement, One Transaction

Without BEGIN, every statement is its own transaction and commits immediately. That's fine for single changes, and dangerous for pairs. Here the enrollment succeeds, then the payment fails a check (a negative amount), and the enrollment stays:

SQL▶ Try it
INSERT INTO enrollments VALUES (102, 5, '2026-01-05', 'active');
 
INSERT INTO payments (student_id, course_id, amount_usd, due_on, paid_on, method)
VALUES (102, 5, -225.00, '2026-01-05', '2026-01-05', 'card');
 
SELECT count(*) AS enrolled_without_payment
FROM enrollments
WHERE student_id = 102 AND course_id = 5;
Output
INSERT 0 1
 
ERROR:  new row for relation "payments" violates check constraint "payments_amount_usd_check"
DETAIL:  Failing row contains (8, 102, 5, -225.00, 2026-01-05, 2026-01-05, card).
 
 enrolled_without_payment
--------------------------
                        1
(1 row)

Half the job was saved. In a transaction, the failed payment would have taken the enrollment down with it.

When a Statement Fails Inside a Transaction

After an error, PostgreSQL marks the transaction as failed and refuses everything until it ends:

SQL▶ Try it
BEGIN;
 
INSERT INTO enrollments VALUES (102, 5, '2026-01-05', 'active');
 
INSERT INTO payments (student_id, course_id, amount_usd, due_on, paid_on, method)
VALUES (102, 5, -225.00, '2026-01-05', '2026-01-05', 'card');
 
SELECT 1;
 
ROLLBACK;
 
SELECT count(*) AS enrolled FROM enrollments WHERE student_id = 102 AND course_id = 5;
Output
BEGIN
 
INSERT 0 1
 
ERROR:  new row for relation "payments" violates check constraint "payments_amount_usd_check"
DETAIL:  Failing row contains (8, 102, 5, -225.00, 2026-01-05, 2026-01-05, card).
 
ERROR:  current transaction is aborted, commands ignored until end of transaction block
 
ROLLBACK
 
 enrolled
----------
        0
(1 row)

current transaction is aborted, commands ignored until end of transaction block: even SELECT 1 was refused. ROLLBACK ends the transaction, and the enrollment is gone, which is exactly what we wanted. If you type COMMIT on a failed transaction, PostgreSQL rolls it back anyway, and psql reports ROLLBACK. Other databases differ here: SQL Server and MySQL keep the transaction open after most errors and let later statements run, so your code must decide whether to roll back.

The bad payment fails; every later statement is refused until ROLLBACK, which also undoes the enrollment

Savepoints

SAVEPOINT name marks a spot inside a transaction; ROLLBACK TO SAVEPOINT name undoes only what came after it. The enrollment is kept, the bad payment is undone, and a corrected payment is recorded, all in one transaction:

SQL▶ Try it
BEGIN;
 
INSERT INTO enrollments VALUES (102, 5, '2026-01-05', 'active');
 
SAVEPOINT before_payment;
 
INSERT INTO payments (student_id, course_id, amount_usd, due_on, paid_on, method)
VALUES (102, 5, -225.00, '2026-01-05', '2026-01-05', 'card');
 
ROLLBACK TO SAVEPOINT before_payment;
 
INSERT INTO payments (student_id, course_id, amount_usd, due_on, paid_on, method)
VALUES (102, 5, 225.00, '2026-01-05', '2026-01-05', 'card');
 
COMMIT;
 
SELECT student_id, course_id, amount_usd FROM payments WHERE student_id = 102;
Output
BEGIN
 
INSERT 0 1
 
SAVEPOINT
 
ERROR:  new row for relation "payments" violates check constraint "payments_amount_usd_check"
DETAIL:  Failing row contains (8, 102, 5, -225.00, 2026-01-05, 2026-01-05, card).
 
ROLLBACK
 
INSERT 0 1
 
COMMIT
 
 student_id | course_id | amount_usd
------------+-----------+------------
        102 |         5 |     225.00
(1 row)

The rollback to the savepoint cleared the error and the bad insert, but kept the enrollment, so the transaction could continue and commit. Savepoints are how programs retry one step without starting over. RELEASE SAVEPOINT name forgets a savepoint you no longer need.

Under the Hood: How a Commit Survives a Crash

When COMMIT returns, the change survives a crash, even a power cut a millisecond later, with the default settings (fsync and synchronous_commit on) and storage that really writes data when asked to. PostgreSQL makes that promise with a write-ahead log (WAL):

  1. Each change is first written as a record to the WAL, an append-only file.
  2. At COMMIT, PostgreSQL forces the WAL records to disk (an fsync) before reporting success. Writing one sequential file is fast.
  3. The changed table pages stay in memory and are written to the table files later, in the background.
  4. After a crash, PostgreSQL replays the WAL from the last checkpoint, redoing every committed change and ignoring uncommitted ones.

That's the "D" in ACID, the four guarantees transactions give:

LetterMeansIn the Fee Tracker
AtomicityAll or nothingThe enrollment and payment are saved together or not at all
ConsistencyRules hold before and afterNo payment without an enrollment, ever
IsolationConcurrent transactions don't see each other's half-done workOthers see the enrollment and payment only after COMMIT
DurabilityCommitted means permanentA power cut after COMMIT loses nothing

Isolation has levels and trade-offs of its own, covered in Isolation Levels.

Changes go to the write-ahead log, which is flushed to disk at COMMIT; table files are updated later and can be rebuilt from the log

Common Mistakes

Running related changes without a transaction. A failure halfway leaves half the work saved.

Forgetting to COMMIT. In a client with autocommit off, or after BEGIN, nothing is saved until you commit; closing the connection rolls back.

Leaving transactions open. An open transaction holds locks and blocks others. Commit or roll back promptly.

Expecting ROLLBACK to undo a commit. Once committed, it's permanent; only a new change can reverse it.

Interview Corner

What is a transaction?

A group of statements treated as one unit of work: either all their changes are committed together, or all are rolled back. Transactions give the ACID guarantees.

What does ACID stand for?

Atomicity (all or nothing), Consistency (constraints hold), Isolation (concurrent transactions don't see each other's uncommitted work) and Durability (committed changes survive crashes).

What is a savepoint?

A named point inside a transaction. ROLLBACK TO SAVEPOINT undoes only the work after it, keeping earlier changes and letting the transaction continue.

How does a database make committed data durable?

With a write-ahead log: changes are recorded in a log that's flushed to disk at commit, and replayed after a crash.

Practice

Challenge (module checkpoint): Inside a transaction, move Advitha (102) from SQL Basics (course 4) to JavaScript Basics (course 5): mark her SQL Basics enrollment 'dropped', enroll her in course 5, and record a $225.00 card payment due and paid on 2026-01-05. Show her enrollments, then roll it all back and show them again. (Then, on your own, run it with COMMIT instead.)

Show solution
SQL▶ Try it
BEGIN;
 
UPDATE enrollments SET status = 'dropped'
WHERE student_id = 102 AND course_id = 4;
 
INSERT INTO enrollments VALUES (102, 5, '2026-01-05', 'active');
 
INSERT INTO payments (student_id, course_id, amount_usd, due_on, paid_on, method)
VALUES (102, 5, 225.00, '2026-01-05', '2026-01-05', 'card');
 
SELECT course_id, status FROM enrollments WHERE student_id = 102 ORDER BY course_id;
 
ROLLBACK;
 
SELECT course_id, status FROM enrollments WHERE student_id = 102 ORDER BY course_id;
Output
BEGIN
 
UPDATE 1
 
INSERT 0 1
 
INSERT 0 1
 
 course_id | status
-----------+---------
         1 | active
         4 | dropped
         5 | active
(3 rows)
 
ROLLBACK
 
 course_id | status
-----------+--------
         1 | active
         4 | active
(2 rows)

Inside the transaction, she's dropped from SQL Basics and active in JavaScript Basics; after ROLLBACK, everything is exactly as before. Replace ROLLBACK with COMMIT, and all three changes are saved together.

Quick check: Transactions

3 questions
1BEGIN; two INSERTs; ROLLBACK;. How many rows are saved?
2Inside a transaction, a statement fails. What does PostgreSQL do with the next SELECT?
3What makes a committed change survive a power cut?

Key Takeaways

You want toWrite
Group changesBEGIN; ... COMMIT;
Undo everythingROLLBACK;
Mark a retry pointSAVEPOINT before_payment;
Undo part of itROLLBACK TO SAVEPOINT before_payment;

Was this tutorial helpful?

Lesson 61 of 115