MySQL
Transactions
Use BEGIN, COMMIT, ROLLBACK, and isolation levels.
By EZ4Code Team
transactionacidlocking
Code
-- Start a transaction
START TRANSACTION;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
-- Confirm or revert
COMMIT;
-- ROLLBACK;
-- Set isolation level
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;
-- Lock rows for update within a transaction
START TRANSACTION;
SELECT balance FROM accounts WHERE id = 1 FOR UPDATE;
-- perform business logic
UPDATE accounts SET balance = balance - 50 WHERE id = 1;
COMMIT;Explanation
Transactions group statements into an atomic unit, either all committed or all rolled back. MySQL's default InnoDB isolation level is REPEATABLE READ, preventing non-repeatable reads within a transaction. SELECT ... FOR UPDATE acquires write locks to safely read-then-update under concurrency.
More MySQL Snippets
SELECT with JOINs
Combine rows from multiple tables using JOINs.
Subqueries
Use scalar, IN, EXISTS, and derived-table subqueries.
Indexes
Create single, composite, unique, and fulltext indexes.
Stored Procedures
Define reusable procedural routines with parameters.
Triggers
Run logic automatically on INSERT, UPDATE, or DELETE.
Views
Create virtual tables to simplify and secure queries.