Basic Transactions: Concept
Module: SQL Fundamentals
A transaction is a group of SQL statements that execute as a single unit. Either all statements succeed (COMMIT) or all fail (ROLLBACK). Transactions ensure data consistency and prevent partial updates.
**Transaction Basics:**
- BEGIN: Start a transaction
- COMMIT: Save all changes permanently
- ROLLBACK: Undo all changes since BEGIN
**ACID Properties:**
- **Atomicity**: All or nothing (no partial updates)
- **Consistency**: Data remains valid (constraints enforced)
- **Isolation**: Transactions don't interfere with each other
- **Durability**: Committed changes are permanent
**Why Use Transactions:**
1. **Data Integrity**: Ensure related changes happen together
2. **Error Recovery**: Rollback on failure
3. **Consistency**: Maintain valid state
4. **Safety**: Test changes before committing
**Transaction Flow:**
1. BEGIN TRANSACTION
2. Execute SQL statements (INSERT, UPDATE, DELETE)
3. If all succeed: COMMIT
4. If any fail: ROLLBACK
**Auto-commit Mode:**
- By default, each statement is a transaction
- Explicit transactions override auto-commit
- Use BEGIN to start multi-statement transaction
Transactions are fundamental to data integrity. Every financial system, e-commerce platform, and critical application uses transactions. Understanding transactions prevents data corruption, ensures consistency, and enables safe error handling. Essential for backend developers and DBAs.
A bank transfer moves $100 from Account A to Account B. This requires two operations: (1) Subtract $100 from A, (2) Add $100 to B. If operation 1 succeeds but 2 fails, money disappears! Transactions ensure both operations succeed together or both fail - no partial updates.