Database Transactions Explained
Definition
A database transaction is a sequence of SQL operations executed as a single atomic unit — all operations succeed together or all are rolled back, leaving the database in a consistent state.
Introduction to Database Transactions Explained
Transactions are the safety mechanism that makes relational databases reliable for critical operations like financial transfers, order processing, and inventory management. Without transactions, a server crash mid-operation could leave data in an inconsistent state — money debited but not credited, orders created but not fulfilled.
Key Takeaways
- Atomicity: all-or-nothing — partial commits are impossible
- Consistency: constraints, triggers, and rules are enforced on every commit
- Isolation: concurrent transactions don't see each other's uncommitted work
- Durability: committed data survives power failures (written to WAL/redo log first)
- Isolation levels trade consistency guarantees for concurrency performance
- Deadlocks are automatically detected; one transaction is chosen as the victim
Real-World Examples & SQL Schema
Bank Transfer Transaction
BEGIN; UPDATE accounts SET balance = balance - 500 WHERE id = 1; UPDATE accounts SET balance = balance + 500 WHERE id = 2; -- Only commit if both updates succeeded COMMIT; -- On any error: -- ROLLBACK;
The transfer is atomic — either both updates happen or neither does. No partial state is possible.
Run code in PlaygroundIsolation Levels
-- Set isolation level for a session SET TRANSACTION ISOLATION LEVEL READ COMMITTED; BEGIN; SELECT balance FROM accounts WHERE id = 1; -- reads committed data COMMIT; -- Highest isolation (slowest): SET TRANSACTION ISOLATION LEVEL SERIALIZABLE; BEGIN; SELECT SUM(balance) FROM accounts; -- repeatable, no phantoms COMMIT;
Higher isolation levels prevent more anomalies but reduce concurrency.
Run code in PlaygroundPrimary Use Cases
Financial operations (transfers, payments, billing)
Order processing (create order + reduce inventory atomically)
User registration (create account + send verification atomically)
Data migrations that must be reversible
Batch operations where partial success is worse than complete failure