VillageSQL is a drop-in replacement for MySQL with extensions.
All examples on this page work on VillageSQL. Install Now →
sakila_practice database from
INSERT. Run the setup block there again before you start,
then open the client with mysql -u root -p sakila_practice.
How a transaction works
FIRST_STATEMENT and SECOND_STATEMENT with the statements that have
to succeed together.
COMMIT makes the work permanent and visible to everyone else. ROLLBACK
throws it away and puts the rows back as they were. Until you type one of the 2,
the changes are yours alone: another session still sees the old values.
Every statement outside a transaction commits by itself, because autocommit
is on.
COMMIT: each INSERT and UPDATE
was a transaction of 1 statement. START TRANSACTION suspends that until you
finish.
Examples
1) Undo the work with ROLLBACK
SELECT inside the transaction reports 400 and 350, because a session sees
its own uncommitted work. The ROLLBACK then undoes both updates.
2) Keep the work with COMMIT
Some statements commit without being asked
A statement that changes the shape of the database cannot be rolled back. Worse, running one commits whatever the open transaction had done up to that point.ROLLBACK.
CREATE TABLE committed the update before it ran, so the
ROLLBACK had nothing left to undo and still reported success. ALTER TABLE,
DROP TABLE, TRUNCATE TABLE and RENAME TABLE behave the same way. Keep all
5 out of a transaction that is protecting data.
Temporary tables are the exception. CREATE TEMPORARY TABLE and
DROP TEMPORARY TABLE commit nothing, so the same test with a temporary table
in the middle leaves the balance at 500.00.
Summary
- Write
START TRANSACTION, then the statements, thenCOMMITorROLLBACK. - Expect every statement outside a transaction to commit by itself, because
autocommitis on. - Expect your session to see its own uncommitted changes and no other session to see them.
- Treat
ROLLBACKas the only undo there is. - Keep
CREATE TABLE,ALTER TABLE,DROP TABLE,TRUNCATE TABLEandRENAME TABLEout of a transaction, because each one commits it. - Expect the
TEMPORARYforms ofCREATEandDROPto commit nothing.
See also
- UPDATE — the statement most worth wrapping in a transaction
- DELETE — removing rows you may want back
- Transactions in MySQL — isolation levels, locking and what they cost
- Deadlocks in MySQL — what happens when 2 transactions want the same rows

