đŗ A Transaction in SQL is a sequence of one or more SQL statements executed as a single logical unit of work. A transaction ensures that either all operations succeed or none of them are applied, protecting the consistency and integrity of the database.
đ What is a Transaction?
A transaction groups multiple database operations into one unit. If every statement executes successfully, the changes are permanently saved. If any operation fails, the database can undo all changes made during the transaction, returning the database to its previous consistent state.
Information
đ¯ Why Use Transactions?
Transactions ensure reliable and consistent database operations, especially when multiple SQL statements depend on each other.
- đ Maintain data consistency.
- đ Prevent partial updates.
- đ Recover safely from errors.
- đ Protect data during concurrent access.
- đ Ensure business operations complete correctly.
đĄ Real-World Example
Imagine transferring money from one bank account to another:
- Withdraw money from Account A.
- Deposit money into Account B.
If the withdrawal succeeds but the deposit fails, the database must undo the withdrawal to prevent money from disappearing. A transaction guarantees that both operations succeed together or both are rolled back.
đ Basic Transaction Syntax
Transaction Syntax
BEGIN TRANSACTION;
-- SQL statements
COMMIT;đ Transaction Lifecycle
| Step | Description |
|---|---|
| BEGIN TRANSACTION | Starts a new transaction. |
| Execute SQL | Run one or more SQL statements. |
| COMMIT | Permanently save all changes. |
| ROLLBACK | Undo all changes made during the transaction. |
đž Commit a Transaction
A COMMIT permanently saves all successful changes.
Commit Example
BEGIN TRANSACTION;
UPDATE Accounts
SET Balance = Balance - 500
WHERE AccountID = 101;
UPDATE Accounts
SET Balance = Balance + 500
WHERE AccountID = 102;
COMMIT;After the COMMIT, both account balances are permanently updated.
âŠī¸ Roll Back a Transaction
If an error occurs, ROLLBACK restores the database to its previous state.
Rollback Example
BEGIN TRANSACTION;
UPDATE Accounts
SET Balance = Balance - 500
WHERE AccountID = 101;
-- An unexpected error occurs
ROLLBACK;The withdrawal is undone because the transaction was rolled back.
đ Savepoints
A SAVEPOINT creates a checkpoint within a transaction. Instead of rolling back the entire transaction, you can roll back only to a specific savepoint if supported by your database system.
Using a Savepoint
BEGIN TRANSACTION;
INSERT INTO Orders (...)
VALUES (...);
SAVEPOINT OrderCreated;
UPDATE Inventory
SET Quantity = Quantity - 1;
-- If needed:
ROLLBACK TO SAVEPOINT OrderCreated;
COMMIT;Important
đĄī¸ ACID Properties
Every reliable transaction follows the ACID principles.
| Property | Description |
|---|---|
| Atomicity | All operations succeed together or all fail together. |
| Consistency | The database remains in a valid state before and after the transaction. |
| Isolation | Concurrent transactions do not interfere with each other. |
| Durability | Committed changes survive system failures. |
Remember
đ Transaction Workflow
| Stage | Action |
|---|---|
| 1 | Start the transaction. |
| 2 | Execute SQL statements. |
| 3 | If successful, execute COMMIT. |
| 4 | If an error occurs, execute ROLLBACK. |
âī¸ COMMIT vs ROLLBACK
| Feature | COMMIT | ROLLBACK |
|---|---|---|
| Purpose | Save changes. | Undo changes. |
| Data Modified | Permanent. | Restored to the previous state. |
| Used After Success | â Yes | â No |
| Used After Failure | â No | â Yes |
đŧ Real-World Applications
- đĻ Bank fund transfers.
- đ Online order processing.
- đī¸ Ticket reservation systems.
- đĻ Inventory management.
- đŗ Payment processing.
- đĨ Hospital and patient management systems.
đī¸ Database Compatibility
| Database System | Transaction Support |
|---|---|
| MySQL | â Supported by transactional storage engines such as InnoDB. |
| PostgreSQL | â Full ACID-compliant transaction support. |
| SQL Server | â Comprehensive transaction management. |
| Oracle | â Full transaction support with savepoints. |
| SQLite | â Supports transactions, including savepoints. |
â ī¸ Common Mistakes
- â Forgetting to commit successful transactions.
- â Leaving transactions open for too long, causing unnecessary locking.
- â Ignoring error handling and rollback logic.
- â Assuming every SQL statement automatically belongs to the same explicit transaction.
Warning
â ī¸ Best Practices
Best Practice
đ Key Points to Remember
- đ A transaction groups multiple SQL statements into one logical unit.
- đ Transactions guarantee all-or-nothing execution.
- đ COMMIT permanently saves changes.
- đ ROLLBACK reverses uncommitted changes.
- đ Savepoints enable partial rollbacks in many database systems.
- đ ACID properties ensure reliable and consistent transaction processing.