SQL transactions: BEGIN, COMMIT and ROLLBACK

Some changes only make sense together: take 30 packs out of the East warehouse and book them into the West one. A transaction bundles those statements into one unit that either happens completely or not at all.

In short: BEGIN; starts a transaction. The changes that follow only count as saved once you run COMMIT;. ROLLBACK; throws away everything since BEGIN instead.

What you should know first: changing data with UPDATE and INSERT, plus primary and foreign keys.

Try it now

Write several statements one below the other and end each with a semicolon. After they run, the exercise shows you the table as it now stands.

Task The East warehouse is sending 30 packs of copy paper (product_id 1) to the West warehouse. Record the transfer in warehouse_stock: 30 fewer in East, 30 more in West. Both changes belong together, so put them in one transaction with BEGIN and COMMIT.

warehouse_stock 8 rows, 3 columns
warehouseproduct_idquantity
East1260
East2200
East3120
East640
West1160
West2110
West365
West624

How a transaction works

Without BEGIN, the database saves every change on its own the moment it finishes. That's called autocommit, and it's the default in SQLite, MySQL and PostgreSQL. For a stock transfer that's risky: if the server goes down between the first and the second UPDATE, 30 packs have left East and never arrived in West.

BEGIN;
UPDATE warehouse_stock SET quantity = quantity - 30
WHERE warehouse = 'East' AND product_id = 1;
UPDATE warehouse_stock SET quantity = quantity + 30
WHERE warehouse = 'West' AND product_id = 1;
COMMIT;

Between BEGIN and COMMIT the changes are provisional. COMMIT makes both of them permanent at once. If anything breaks before that, neither change is there after a restart. Afterwards, the copy paper stock looks like this:

warehouseproduct_idquantity
East1230
West1190

Together that's still 420 packs, matching the stock in products. A transaction makes sure totals like this are never wrong, not even for a moment.

ROLLBACK: back to square one

Write ROLLBACK instead of COMMIT and the database discards every change since BEGIN, as if nothing had happened. That's handy for a dry run: make the change, check its effect with SELECT, undo it. In these exercises you always see the state after all your statements have run; a SELECT in the middle isn't displayed. So you can still tell what your dry run did, the next exercise counts the rows deleted between BEGIN and ROLLBACK.

Task Raj Patel (customer_id 4) has asked for his data to be erased. Before that happens for real, accounting needs to check whether his orders have to be kept for the records. Do a dry run: start a transaction, delete his line items, his orders and then him from customers, and undo everything at the end with ROLLBACK. Afterwards the exercise shows how many customers, orders and line items there are, and in deleted_in_dry_run how many rows your dry run had deleted.

customers 12 rows, 7 columns
customer_idnamecitycountrycustomer_sincesegmentphone
1Harbor Fremont PartnersBostonUSA2021-03-15Business617-555-0142
2Emily CarterChicagoUSA2022-07-01ConsumerNULL
3Riverside County OfficeRiversideUSA2020-11-20Government951-555-0110
4Raj PatelLeedsUK2023-01-09Consumer0113 496 0123
5Lakeview Hotel LtdManchesterUK2022-04-18Business0161 496 0456
6Olivia BrooksAustinUSA2024-02-27ConsumerNULL
7Greene & Shaw LLPLondonUK2021-09-05Business020 7946 0321
8Maple Grove High SchoolAustinUSA2023-08-14School512-555-0187
9Chloe EvansBostonUSA2025-05-30Consumer617-555-0199
10Northline Printing CoTorontoCanada2020-06-12Business416-555-0133
11Daniel KimSeattleUSA2024-10-03ConsumerNULL
12Westbrook Dental ClinicChicagoUSA2022-12-01Business312-555-0164
orders 18 rows, 5 columns
order_idcustomer_idorder_datestatusemployee_id
100112026-01-08delivered3
100242026-01-12delivered4
100332026-01-20delivered3
100472026-02-03delivered4
100522026-02-11cancelled8
100612026-02-25delivered3
1007102026-03-04delivered2
100852026-03-17delivered4
100982026-03-30delivered3
101062026-04-07delivered8
1011122026-04-22delivered4
101232026-05-06delivered3
101392026-05-19cancelled8
101472026-06-02shipped4
101512026-06-10shipped3
1016112026-06-12openNULL
101742026-06-13openNULL
1018102026-06-14openNULL
order_items 38 rows, 4 columns
order_idproduct_idquantityunit_price
10011404.79
10013252.79
10016424.9
1002223.49
10021035.49
10031604.69
100311684.9
10033502.59
100443179
100493269
100551449
10061304.79
10067106.99
100782219
100711489.9
10071204.99
100846175
1008253.49
1009101204.99
10092403.19
100992279
1010726.99
1010213.49
1011121129
10111104.99
10113122.79
10126823.9
10121404.69
101391279
101452439
101442179
10151504.79
101511289.9
10161045.49
1017233.49
1017726.99
10181804.79
101861024.9

This exercise is part of Premium.

Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.

See Premium Already Premium? Log in

The first exercise in this lesson is free.

What happens when a statement fails

An error inside a transaction doesn't automatically undo everything. When a rule such as a duplicate key or a missing required value is broken, SQLite backs out only the statement that failed. The transaction stays open and the decision is yours: ROLLBACK or carry on. PostgreSQL puts the transaction into an aborted state after an error, and only ROLLBACK or ROLLBACK TO gets you out of it. SQL Server rolls the whole transaction back on any run-time error if SET XACT_ABORT ON is in effect. So don't count on any of it: after an error, issue an explicit ROLLBACK.

SAVEPOINT: undo just part of it

A savepoint is a marker inside a transaction. ROLLBACK TO name undoes only what came after the marker, and the transaction carries on:

BEGIN;
UPDATE products SET price = ROUND(price * 1.05, 2) WHERE category = 'Paper';
SAVEPOINT before_electronics;
UPDATE products SET price = ROUND(price * 1.05, 2) WHERE category = 'Electronics';
ROLLBACK TO before_electronics;
COMMIT;

Afterwards copy paper costs 5.24 instead of 4.99 and the notebook 5.76 instead of 5.49, while electronics keep their old prices.

One more exercise: an order as one unit

A new order touches three tables. Watch the order of your statements: the foreign key is checked on every single statement, even inside a transaction.

Task Olivia Brooks (customer_id 6) orders two monitors (product_id 9) on 2026-06-16. Record the order as one unit: in a single transaction, create order 1020 with status open and no employee, add its line item at the current price from products, and take the two units off the stock.

orders 18 rows, 5 columns
order_idcustomer_idorder_datestatusemployee_id
100112026-01-08delivered3
100242026-01-12delivered4
100332026-01-20delivered3
100472026-02-03delivered4
100522026-02-11cancelled8
100612026-02-25delivered3
1007102026-03-04delivered2
100852026-03-17delivered4
100982026-03-30delivered3
101062026-04-07delivered8
1011122026-04-22delivered4
101232026-05-06delivered3
101392026-05-19cancelled8
101472026-06-02shipped4
101512026-06-10shipped3
1016112026-06-12openNULL
101742026-06-13openNULL
1018102026-06-14openNULL
order_items 38 rows, 4 columns
order_idproduct_idquantityunit_price
10011404.79
10013252.79
10016424.9
1002223.49
10021035.49
10031604.69
100311684.9
10033502.59
100443179
100493269
100551449
10061304.79
10067106.99
100782219
100711489.9
10071204.99
100846175
1008253.49
1009101204.99
10092403.19
100992279
1010726.99
1010213.49
1011121129
10111104.99
10113122.79
10126823.9
10121404.69
101391279
101452439
101442179
10151504.79
101511289.9
10161045.49
1017233.49
1017726.99
10181804.79
101861024.9
products 12 rows, 5 columns
product_idnamecategorypricestock
1Copy paper, 500 sheetsPaper4.99420
2Blue ballpoint pens, 10-packWriting3.49310
3Lever arch file, grayFiling2.79185
4Comfort office chairFurniture18912
5Standing deskFurniture4495
6Black ink cartridgePrinter supplies24.964
7Yellow sticky notes, 12 padsWriting6.990
8Mono laser printer L30Electronics2198
927-inch monitorElectronics27915
10Notebook A5, ruledPaper5.49140
11Black toner XLPrinter supplies89.922
12Cross-cut shredderElectronics1290

This exercise is part of Premium.

Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.

See Premium Already Premium? Log in

The first exercise in this lesson is free.

ACID in plain English

What a transaction promises is usually summed up in four letters:

  • Atomic: all or nothing. Both stock movements, or neither.
  • Consistent: once the transaction ends, every rule on the tables holds again: foreign keys, NOT NULL, CHECK.
  • Isolated: other people don't see your half-finished changes. In the words of the PostgreSQL docs, updates made by an open transaction stay invisible to other transactions until it completes, and then they all become visible at once.
  • Durable: once COMMIT has confirmed it, it stays saved, even if the power cuts out a second later.

Isolation only matters when several people work on the same database at the same time. Every time you run or check an exercise here, it starts from a fresh database, so you can't try that part here. One habit to take to work: keep transactions short. Microsoft warns that in SQL Server, transactions left open for a long time can lock data other sessions are waiting for.

Common mistakes

Forgetting BEGIN or COMMIT

Without BEGIN each UPDATE runs on its own. The result is right, but it isn't a transaction, and the exercise says "Solve this one with BEGIN". Leave out COMMIT and the transaction stays open; the message then names COMMIT.

ROLLBACK or COMMIT without BEGIN

The exercise then says "No transaction is running. COMMIT and ROLLBACK need a BEGIN first." In a real database, the changes before it would already be saved by then.

Deleting or inserting in the wrong order

Delete orders before their line items, or add a line item before its order, and the statement fails on the foreign key; the exercise reports a foreign key error. When inserting, the new row points to nothing; when deleting, other rows still point to the one you're trying to remove. That holds in a dry run before ROLLBACK too.

START TRANSACTION in the exercises

That's the MySQL spelling. SQLite doesn't know it, and the exercise rejects the statement. Use BEGIN.

Typing in fixed values

SET quantity = 230 is only right with today's data. The check also runs on different stock levels and then reports "The result is right with this data but not with other data". Work from the current value: quantity = quantity - 30.

Transactions in MySQL, PostgreSQL, SQL Server and SQLite

DatabaseStartSavepointBack to the savepoint
MySQLSTART TRANSACTION (BEGIN works too)SAVEPOINT nameROLLBACK TO SAVEPOINT name
PostgreSQLBEGINSAVEPOINT nameROLLBACK TO name
SQL ServerBEGIN TRANSACTION or BEGIN TRANSAVE TRANSACTION nameROLLBACK TRANSACTION name
SQLite (these exercises)BEGINSAVEPOINT nameROLLBACK TO name

COMMIT and ROLLBACK are called that everywhere; SQL Server also accepts COMMIT TRANSACTION. In SQLite, END is another name for COMMIT. One MySQL trap: statements such as CREATE TABLE, ALTER TABLE, CREATE VIEW and DROP VIEW quietly end an open transaction with a COMMIT, so a later ROLLBACK can't bring the earlier changes back. MySQL also saves changes to tables in a storage engine without transaction support immediately, even inside a transaction. InnoDB, the usual engine, does support transactions.

Sources: MySQL Reference Manual (START TRANSACTION, COMMIT, and ROLLBACK; SAVEPOINT; Statements That Cause an Implicit Commit), PostgreSQL documentation (Tutorial: Transactions), Microsoft Learn (BEGIN TRANSACTION, SAVE TRANSACTION), sqlite.org (Transaction, Savepoints, ON CONFLICT).

Frequently asked questions

Does a single UPDATE need a transaction?

No. A single statement already runs as its own small transaction: an UPDATE across 100 rows changes all 100 or none. You need BEGIN and COMMIT when several statements belong together.

Can I roll back a CREATE TABLE?

In SQLite, yes: CREATE TABLE and DROP TABLE are part of the transaction there. In MySQL, no, because those statements commit the transaction first.

Can I nest transactions?

SQLite refuses a second BEGIN inside an open transaction. Savepoints are the tool for checkpoints within one. SQL Server does accept an inner BEGIN TRANSACTION, but a ROLLBACK still rolls back the whole outer transaction.

Up next: level 4 project, inventory

Everything from level 4 comes together: you book a goods receipt with a new table, INSERT … SELECT and a transaction, then tidy up the product range with UPDATE, DELETE and a view.

Go to the inventory project

Write to us

Choose language

Select your preferred language