Transactions (BEGIN, COMMIT, ROLLBACK, SAVEPOINT)
Group statements into atomic units with BEGIN, COMMIT, ROLLBACK, and SAVEPOINT.
In plain words
Start a transaction, make your changes, then either save them all or throw them all away.
Think of it like…
Drafting an email: you can write, delete and rewrite as much as you like (inside the transaction), and nothing reaches anyone until you press send (COMMIT). Discarding the draft (ROLLBACK) leaves no trace. A savepoint is like saving a version of the draft you can go back to.
Where you’ve seen it
Placing an order: BEGIN; INSERT INTO orders …; INSERT INTO order_items …; UPDATE inventory SET stock = stock - 1 WHERE …; COMMIT;. If the inventory update fails, a ROLLBACK removes the order and its items too, so no half-finished order remains.
Words you’ll hear
- Autocommit
- The default mode in most clients: each statement is its own transaction.
- COMMIT / ROLLBACK
- Make all changes permanent / undo all changes since BEGIN.
- SAVEPOINT
- A named point inside a transaction for a partial rollback.
- Aborted transaction
- In PostgreSQL, after an error every later statement fails until you ROLLBACK.
Visual diagram
Theory & example queries
BEGIN, COMMIT, ROLLBACK and autocommit
In autocommit mode, which psql, MySQL clients and most drivers use by default, each statement is committed as soon as it succeeds. BEGIN switches that off until COMMIT or ROLLBACK, so the statements in between act as one unit, and other sessions don't see the changes until COMMIT.
Frameworks usually manage this for you, through Django's atomic(), Spring's @Transactional or Rails' transaction do. They commit when the block finishes and roll back if it raises an exception. It's still worth knowing what they issue underneath, especially when nesting blocks.
| id | name | price | category | stock |
|---|---|---|---|---|
| 42 | SQL Notebook | 49.5 | books | 18 |
| 84 | Mechanical Keyboard | 150 | hardware | 5 |
| 11 | Query Mug | 12.99 | gifts | 33 |
BEGIN;UPDATE productsSET price = 0;PostgreSQL is the lesson baseline unless noted otherwise.
Open a transaction so changes can be checked and committed or rolled back together.
ROLLBACK;PostgreSQL is the lesson baseline unless noted otherwise.
Read this line together with the surrounding statement as part of the same SQL expression.
Rolled-back update
Note: Assumes seven product rows match the UPDATE. ROLLBACK undoes the mistaken change, so persisted prices remain unchanged.
Oops, no WHERE clause.
Nothing changes, which is why many people run risky manual updates inside a transaction first.
Key takeaway: Without BEGIN, every statement commits on its own.
Savepoints and the aborted-transaction state
In PostgreSQL, once any statement in a transaction fails, the transaction is aborted: every later command returns "current transaction is aborted, commands ignored until end of transaction block" until you ROLLBACK. Savepoints let you recover: set one before a risky statement, and if it fails, ROLLBACK TO SAVEPOINT and carry on. Frameworks implement nested transaction blocks this way.
Keep transactions short. An open transaction holds row locks, blocks other writers, and in PostgreSQL also prevents VACUUM from cleaning up old row versions, so a session left "idle in transaction" for hours slowly bloats tables. Never wait for user input or a slow external API while a transaction is open.
| id | customer_id | status | amount | coupon_code |
|---|---|---|---|---|
| 101 | 1 | paid | 249 | NULL |
| 102 | 2 | paid | 120 | WELCOME10 |
| 103 | 1 | shipped | 89.5 | NULL |
BEGIN;INSERT INTO orders …;SAVEPOINT s1;INSERT INTO coupons_used …;PostgreSQL is the lesson baseline unless noted otherwise.
Open a transaction so changes can be checked and committed or rolled back together.
ROLLBACK TO SAVEPOINT s1;COMMIT;PostgreSQL is the lesson baseline unless noted otherwise.
Read this line together with the surrounding statement as part of the same SQL expression.
Expected recovery at the savepoint
Note: Representative PostgreSQL responses for an order insert followed by a duplicate coupon insert; the order is retained and only coupon work is undone.
fails on a duplicate, so
keeps the order and undoes only the coupon insert.
Key takeaway: Use savepoints for partial recovery; never leave transactions idle.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Open the transaction
Start a transaction before the first statement that must be grouped with others.
BEGIN;When to use it & trade-offs
What it is
A transaction groups statements so they succeed or fail together. BEGIN (or START TRANSACTION) opens it, COMMIT makes every change permanent, and ROLLBACK undoes them all. SAVEPOINT name marks a point inside the transaction you can return to with ROLLBACK TO SAVEPOINT name, without abandoning the earlier work.
Why it matters: Without a transaction, a failure halfway through a multi-step change, such as an order created without its items, leaves the data inconsistent. Most databases run in autocommit mode, so every statement commits on its own unless you open a transaction. Knowing these commands and their pitfalls is basic backend knowledge.
When to reach for it
- Creating an order with its items and stock changes
- Running risky manual updates so you can roll back
- Data migrations that must apply fully or not at all
When to avoid or be careful
- Leaving transactions open while waiting on users or external services
- Relying on autocommit for multi-step changes
- Ignoring PostgreSQL's aborted-transaction state and wondering why later statements fail
Autocommit vs explicit transaction vs savepoints
Strengths: Simple; locks released immediately.
Watch out: Multi-step changes can be left half-done.
Strengths: All-or-nothing; others see a consistent result.
Watch out: Holds locks until the end; must be kept short.
Strengths: Partial rollback; enables nested blocks in frameworks.
Watch out: Adds overhead and complexity when overused.
Interview signals & numbers to know
When this topic comes up
- “What happens if the second insert fails?”
- "current transaction is aborted" errors
- "idle in transaction" sessions
- “What is a savepoint?”
- Framework transaction decorators
Benchmarks & rules of thumb
- 1
- transaction per statement in autocommit mode
- COMMIT
- makes changes visible to other sessions
- SAVEPOINT
- partial rollback point
Common mistakes & follow-ups
Common interview mistakes
- Running a multi-step change in autocommit mode and leaving half of it applied after an error.
- Continuing to send statements after an error in a PostgreSQL transaction instead of rolling back.
- Holding a transaction open across an HTTP call to a payment provider.
Likely interviewer follow-ups
- What is autocommit, and why does it matter for multi-step changes?
- How do savepoints work, and when would you use one?
- Why are long-running transactions a problem in PostgreSQL?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Transactions (BEGIN, COMMIT, ROLLBACK, SAVEPOINT) with hands-on SQL practice and interview Q&A.