Transactions and ACID Properties
# CHAPTER 20
Transactions and ACID Properties
1. Introduction
Imagine you are building a banking application. A user transfers $1,000 to their friend. This requires two SQL queries:-
1.
UPDATE accounts SET balance = balance - 1000 WHERE user = 'A';
-
2.
UPDATE accounts SET balance = balance + 1000 WHERE user = 'B';
What happens if the server loses power exactly one microsecond *after* query 1 finishes, but *before* query 2 runs? User A lost their money, but User B never got it. The $1,000 evaporated into digital thin air. This is the ultimate nightmare of database administration. To solve it, we bundle queries into Transactions, governed by the laws of ACID.
2. Learning Objectives
By the end of this chapter, you will be able to:- Explain the four ACID properties of a database.
-
Start a MySQL Transaction using
START TRANSACTION.
-
Permanently save a transaction using
COMMIT.
-
Abort and undo a transaction using
ROLLBACK.
- Prevent partial data corruption in critical workflows.
3. What are ACID Properties?
For a database engine (like MySQL's InnoDB) to be considered "Enterprise-grade," it must guarantee four strict laws of physics known as ACID:- Atomicity: "All or Nothing." A transaction of 5 queries must completely succeed, or completely fail. If query 4 fails, queries 1, 2, and 3 are automatically undone. No partial updates exist.
-
Consistency: The database must move from one valid state to another. All
CHECKandFOREIGN KEYconstraints must be satisfied before and after.
- Isolation: If 1,000 users are transferring money at the exact same millisecond, their transactions must run in isolation. They cannot mathematically interfere with each other's calculations.
-
Durability: Once a transaction is
COMMITted, it is permanently written to the physical hard drive. Even if the server explodes 1 second later, the data is safe.
4. Writing a Transaction
By default, MySQL operates in "Autocommit" mode. Every singleUPDATE or INSERT you type is instantly saved.
To bundle queries, we manually disable autocommit for a block of code using START TRANSACTION.
*Once COMMIT executes, the money transfer becomes a permanent, durable reality.*
5. The Power of ROLLBACK
Let's recreate the server failure scenario. You start the transaction, deduct the money, but before you can add it, a constraint error occurs (or you realize you made a mistake).
*When ROLLBACK executes, the database engine time-travels backward. The $1,000 deduction from ID 1 is instantly erased as if it never happened. Atomicity is preserved!*
6. Mini Project: E-Commerce Checkout
Transactions are mandatory for E-commerce. When a user clicks "Checkout", three things must happen flawlessly:7. Common Mistakes
-
Forgetting to COMMIT: If you run
START TRANSACTION, type 50INSERTcommands, and then close your terminal without typingCOMMIT, MySQL will assume you aborted and will silentlyROLLBACKall 50 commands. Your data will not be saved!
-
Using MyISAM: MySQL supports different internal "storage engines". The modern default is
InnoDB, which fully supports ACID transactions. The olderMyISAMengine does NOT support transactions! If you try toROLLBACKon a MyISAM table, it will fail, and your data will be permanently corrupted.
8. Best Practices
-
Backend Orchestration: You rarely write
START TRANSACTIONin the raw MySQL terminal. You execute it via your application code. In PHP (PDO), you use$conn->beginTransaction(). You put your queries inside atry {}block. If any query throws an exception, thecatch {}block executes$conn->rollBack().
9. Exercises
- 1. Define the "A" in ACID and explain what it prevents.
- 2. What command must you issue to permanently save the changes made during an active transaction?
10. MCQ Quiz with Answers
What is the fundamental purpose of wrapping multiple SQL queries inside a START TRANSACTION and COMMIT block?
If a catastrophic error occurs in the middle of an active transaction, which command should your backend application send to MySQL to undo the partial changes?
11. Interview Questions
- Q: Explain the four ACID properties (Atomicity, Consistency, Isolation, Durability) and why they are critical for a banking database.
- Q: Describe a real-world web application scenario where failing to use a Transaction would result in catastrophic data inconsistency.
12. FAQs
Q: Do Transactions lock the tables? A: Yes! To ensure "Isolation", InnoDB utilizes "Row-Level Locking". If Transaction A is currently updating User 1's balance, and Transaction B tries to update User 1, Transaction B will be forced to pause and wait until Transaction A finishes and issues aCOMMIT!
13. Summary
Transactions are the ultimate safety net of database architecture. By embracing the ACID properties and utilizingCOMMIT and ROLLBACK, you ensure that your application can safely execute complex, multi-step financial and relational operations without the terrifying risk of partial data corruption.