MySQL Transactions and Locking Cheatsheet

start transaction, commit, rollback, savepoints, select for update, isolation levels, and InnoDB lock troubleshooting.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all

transactions

Atomic writes, commit, rollback, and savepoints.

Start a transaction

Begin a transaction explicitly.

sqlANYtransactionstart
sql
START TRANSACTION;

Explicit transactions let you group related writes into a single atomic unit.

Commit a transaction

Persist all changes made in the current transaction.

sqlANYcommittransaction
sql
COMMIT;

After `COMMIT`, changes become durable and visible according to isolation semantics.

Rollback a transaction

Undo all uncommitted changes.

sqlANYrollbacktransaction
sql
ROLLBACK;

Crucial when a multi-step operation fails partway through.

Set and rollback to a savepoint

Undo only part of a transaction.

sqlANYsavepointrollback
sql
START TRANSACTION;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
SAVEPOINT after_debit;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
ROLLBACK TO SAVEPOINT after_debit;
COMMIT;

Savepoints are useful when a larger transaction contains optional or retryable steps.

Disable autocommit for the session

Keep statements in a transaction until you commit or rollback.

sqlANYautocommitsession
sql
SET autocommit = 0;

Use carefully; long-lived transactions can hold locks and increase contention.

locking and concurrency

Read and write contention patterns for transactional workloads.

Lock selected rows for update

Prevent concurrent modifications to matched rows inside a transaction.

sqlANYfor-updatelocking
sql
SELECT * FROM accounts WHERE id = 1 FOR UPDATE;

Common in balance transfers, inventory reservations, and queue consumers.

Lock rows for shared reads

Read rows while protecting against conflicting writes.

sqlANYfor-sharelocking
sql
SELECT * FROM products WHERE id = 10 FOR SHARE;

Use shared locks when you want consistency without taking an exclusive update lock.

Set transaction isolation level

Control read consistency and concurrency behavior.

sqlANYisolation-leveltransaction
sql
SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

Isolation level affects phenomena such as dirty reads, nonrepeatable reads, and phantoms.

Inspect InnoDB lock and transaction state

Display detailed InnoDB diagnostics.

sqlANYinnodbdeadlockstatus
sql
SHOW ENGINE INNODB STATUS\G

A classic source of deadlock and locking information during production troubleshooting.

Set lock wait timeout for the session

Avoid waiting too long on blocked locks.

sqlANYlock-wait-timeoutinnodb
sql
SET SESSION innodb_lock_wait_timeout = 10;

Shorter timeouts are often helpful in APIs that should fail fast under contention.

Recommended next

No recommendations yet.