Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 141/ 160
08. Transactions, Security & Production SQL Administration

Transactions (BEGIN, COMMIT, ROLLBACK, SAVEPOINT)

Group statements into atomic units with BEGIN, COMMIT, ROLLBACK, and SAVEPOINT.

BeginnerBEGIN / COMMIT · ROLLBACK3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

Undoing a mistakeQuery example
1Input dataStart from the source rows or state that the statement sees.
products
3 rows
products sample rows
idnamepricecategorystock
42SQL Notebook49.5books18
84Mechanical Keyboard150hardware5
11Query Mug12.99gifts33
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1BEGIN;23UPDATE products4SET5  price = 0;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Start transaction

Open a transaction so changes can be checked and committed or rolled back together.

1/5
query.sql
1ROLLBACK;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · SQL expression

Read this line together with the surrounding statement as part of the same SQL expression.

1/1
3OutputInspect the representative rows, affected-row count, plan, or command status.
Rolled-back update
BEGIN UPDATE 7 ROLLBACK

Note: Assumes seven product rows match the UPDATE. ROLLBACK undoes the mistaken change, so persisted prices remain unchanged.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

Recovering from one failed statementQuery example
1Input dataStart from the source rows or state that the statement sees.
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sqlReadable preview
1BEGIN;2INSERT INTO orders …;3SAVEPOINT s1;4INSERT INTO coupons_used …;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Start transaction

Open a transaction so changes can be checked and committed or rolled back together.

1/4
query.sql
1ROLLBACK TO SAVEPOINT s1;23COMMIT;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · SQL expression

Read this line together with the surrounding statement as part of the same SQL expression.

1/3
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected recovery at the savepoint
BEGIN INSERT 0 1 SAVEPOINT ERROR: duplicate key value violates unique constraint ROLLBACK TO SAVEPOINT COMMIT

Note: Representative PostgreSQL responses for an order insert followed by a duplicate coupon insert; the order is retained and only coupon work is undone.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1BEGIN

Open the transaction

Start a transaction before the first statement that must be grouped with others.

SQL at this step
1BEGIN;
What to watch at this step
Autocommit
off until the end
Tip: use ← → to move between steps

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

Autocommit (no BEGIN)
Best for: Single, independent statements

Strengths: Simple; locks released immediately.

Watch out: Multi-step changes can be left half-done.

Explicit transaction
Best for: Multi-statement changes that must be atomic

Strengths: All-or-nothing; others see a consistent result.

Watch out: Holds locks until the end; must be kept short.

Savepoints inside a transaction
Best for: Recovering from an expected failure without losing earlier work

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?
Interview tip: Explain transactions with one concrete multi-step change (an order with items and stock), say what happens on failure with and without BEGIN, then mention one operational pitfall like idle-in-transaction sessions.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Transactions (BEGIN, COMMIT, ROLLBACK, SAVEPOINT) with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
End-to-End Query Tuning Case Studies (Turning a 30s Query into 30ms)
Next topic
ACID Properties Deep Dive (Atomicity, Consistency, Isolation, Durability)