How to use transactions in SQL
· Category: SQL & Databases
Short answer
A transaction is a sequence of operations performed as a single logical unit of work. Use BEGIN, COMMIT, and ROLLBACK to control transactions.
Steps
- Start a transaction:
BEGIN;orSTART TRANSACTION; - Execute DML statements:
UPDATE accounts SET balance = balance - 100 WHERE id = 1; - Commit if all operations succeed:
COMMIT; - Rollback on failure:
ROLLBACK; - Use savepoints for partial rollbacks:
SAVEPOINT sp1; ROLLBACK TO sp1;
Tips
- Keep transactions as short as possible to reduce locking contention.
- Choose the appropriate isolation level based on consistency and concurrency requirements.
Common issues
- Long-running transactions hold locks and can block other users or cause deadlocks.
- Auto-commit mode can silently commit partial changes if an error occurs between statements.r