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
Start a transaction
START TRANSACTION;

# Begin a transaction explicitly.

Commit a transaction
COMMIT;

# Persist all changes made in the current transaction.

Rollback a transaction
ROLLBACK;

# Undo all uncommitted changes.

Set and rollback to a savepoint
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;

# Undo only part of a transaction.

Disable autocommit for the session
SET autocommit = 0;

# Keep statements in a transaction until you commit or rollback.

## locking and concurrency
Lock selected rows for update
SELECT * FROM accounts WHERE id = 1 FOR UPDATE;

# Prevent concurrent modifications to matched rows inside a transaction.

Lock rows for shared reads
SELECT * FROM products WHERE id = 10 FOR SHARE;

# Read rows while protecting against conflicting writes.

Set transaction isolation level
SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

# Control read consistency and concurrency behavior.

Inspect InnoDB lock and transaction state
SHOW ENGINE INNODB STATUS\G

# Display detailed InnoDB diagnostics.

Set lock wait timeout for the session
SET SESSION innodb_lock_wait_timeout = 10;

# Avoid waiting too long on blocked locks.

Recommended next

No recommendations yet.