, BEGIN, COMMIT, ROLLBACK and Level

Syntax

START TRANSACTION | BEGIN;
-- SQL statements
COMMIT | ROLLBACK;
SET TRANSACTION ISOLATION LEVEL level;

Parameters

ParametersDescriptionExamplesLevel
BEGIN BEGIN; Common
COMMIT COMMIT; Common
ROLLBACK ROLLBACK; Common
SAVEPOINT SAVEPOINT sp1; Advanced
SET TRANSACTION ISOLATION LEVEL Level SET TRANSACTION ISOLATION LEVEL READ COMMITTED; Advanced

Examples

BEGIN; -- UPDATE accounts SET balance = balance - 500.00
WHERE user_id = 1001 AND balance >= 500.00; -- (affected rows = 1)
-- UPDATE accounts SET balance = balance + 500.00
WHERE user_id = 1002; -- INSERT INTO transfer_logs (from_user, to_user, amount, created_at)
VALUES (1001, 1002, 500.00, NOW()); COMMIT;
, and

BEGIN; -- ( WHERE stock >= quantity )
UPDATE products SET stock = stock - 1
WHERE id = 2001 AND stock >= 1; -- affected_rows, 0 Description
-- INSERT INTO orders (order_no, user_id, product_id, total_amount, status)
VALUES ('ORD20260523001', 1001, 2001, 5999.00, 0); COMMIT;
-- ROLLBACK;
,

SAVEPOINT

BEGIN; INSERT INTO orders (order_no, user_id, total_amount)
VALUES ('ORD001', 1001, 100.00); SAVEPOINT before_items; INSERT INTO order_items (order_id, product_id, quantity)
VALUES (LAST_INSERT_ID(), 2001, 2); --, ROLLBACK TO before_items; -- COMMIT;
SAVEPOINT,

and Level

-- Level
SELECT @@transaction_isolation; -- Level
SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; -- Level: -- READ UNCOMMITTED()
-- READ COMMITTED()
-- REPEATABLE READ(MySQL, )
-- SERIALIZABLE(, )
READ COMMITTED

Common Errors

ERROR 1213 (40001): Deadlock found when trying to get lockand more., SQL
Lock wait timeout exceeded; try restarting transaction. : SHOW PROCESSLIST;

Tips

Related Commands