Transactions and ACID Properties
# CHAPTER 23
Transactions and ACID Properties
1. Introduction
Imagine building the backend for a banking app. Alice wants to transfer $100 to Bob. This requires two SQL queries:-
1.
UPDATE accounts SET balance = balance - 100 WHERE name = 'Alice';
-
2.
UPDATE accounts SET balance = balance + 100 WHERE name = 'Bob';
What happens if the server's power supply explodes the exact millisecond *after* Query 1 finishes, but *before* Query 2 starts? Alice loses her money, and Bob never gets it. The data is corrupted. To solve this terrifying scenario, SQL engines employ Transactions and adhere strictly to the ACID Properties.
2. Learning Objectives
By the end of this chapter, you will be able to:- Define the acronym ACID in the context of databases.
- Wrap multiple SQL queries into a single Transaction block.
-
Execute a
COMMITto permanently save data.
-
Execute a
ROLLBACKto undo a catastrophic error.
- Understand the concept of "All or Nothing" execution.
3. The ACID Properties
A Relational Database is considered "Enterprise Grade" because it strictly guarantees the ACID properties for every transaction:- A (Atomicity): "All or Nothing." If a transaction has 5 steps, and step 4 fails, the database automatically undoes steps 1, 2, and 3. Partial success is mathematically impossible.
-
C (Consistency): The database will never process a transaction that violates a constraint (e.g., trying to set a
NOT NULLcolumn toNULL). It will reject the entire transaction.
- I (Isolation): If 1,000 users are modifying the database at the exact same millisecond, the database processes them in a way where they do not interfere with each other.
- D (Durability): Once the database says "Saved", it is permanent. Even if you pull the power cord out of the server one millisecond later, the data is safe on the hard drive.
4. Anatomy of a Transaction
By default, every single SQL command you type runs in "Auto-Commit" mode (it saves instantly). To group multiple commands together, you must manually start a Transaction block.The syntax relies on three keywords:
-
1.
START TRANSACTION(orBEGINin PostgreSQL): Turns off auto-save.
-
2.
COMMIT: Tells the database to permanently save all the pending queries.
-
3.
ROLLBACK: The "Undo" button. Erases all pending queries since the transaction started.
5. The Bank Transfer (A Perfect Transaction)
Let's execute the scenario from the introduction safely.*(If the server crashed during Step 3, the database would automatically trigger a ROLLBACK upon reboot, returning Alice's $100!)*
6. The ROLLBACK Superpower
What if you start a transaction, execute a DELETE command, and realize you made a terrible mistake? Because you haven't COMMITted yet, the data is not actually gone!
*(Result: The customers table is perfectly restored. The transaction is erased).*
7. Mini Project: E-Commerce Checkout
An E-Commerce checkout requires massive Atomicity. We must insert the Order, insert the Order Items, and reduce the Inventory. If any step fails, the whole checkout must fail.*(In modern application code like Node.js or PHP, developers wrap these SQL commands in a try/catch block. If the catch block triggers, the server automatically fires a ROLLBACK command!)*
8. Common Mistakes
-
Forgetting to COMMIT: If you run
START TRANSACTION, run 5UPDATEqueries, and then close your computer without runningCOMMIT, the database assumes you abandoned the transaction and automaticallyROLLBACKs everything! Your updates will vanish.
- Locking the Database: While a Transaction is open, the database puts a "Lock" on the rows you are modifying to satisfy the "Isolation" property. If you open a transaction, go to lunch for an hour, and forget to commit, no one else in the company can modify those rows until you return!
9. Best Practices
-
Keep Transactions Tiny: A transaction should execute in milliseconds. Never put a slow process (like sending an email or generating a PDF) *inside* an open database transaction block. Do the database work,
COMMIT, and then generate the PDF in your Node.js code.
10. Exercises
- 1. What does the "A" in ACID stand for, and what does it mathematically guarantee?
- 2. What SQL command serves as the "Undo" button for a pending transaction block?
11. SQL Challenges
You are processing a refund. Write a Transaction block thatUPDATEs an order status to 'Refunded', and then UPDATEs the customer's wallet balance by adding 50. End the block by permanently saving the changes.
12. MCQ Quiz with Answers
In the context of Relational Databases, what is the fundamental purpose of the START TRANSACTION and COMMIT commands?
Which of the ACID properties guarantees that once a COMMIT statement executes successfully, the data is permanently safe, even if the database server suffers a catastrophic power failure one millisecond later?
13. Interview Questions
- Q: Define the ACID properties. Explain why a NoSQL database (which often relaxes these properties for speed) would be a terrifying architectural choice for a core banking application.
-
Q: Explain the mechanical interaction between a backend server's
try/catcherror-handling block and the SQLCOMMIT/ROLLBACKcommands during a multi-table E-commerce checkout process.
14. FAQs
Q: DoesROLLBACK work on CREATE TABLE or DROP TABLE commands?
A: In most databases (like MySQL), DDL commands (CREATE, DROP, ALTER) automatically trigger a hidden COMMIT and *cannot* be rolled back! Transactions are almost exclusively used for DML commands (INSERT, UPDATE, DELETE). (Note: PostgreSQL is an exception; it *can* rollback DDL!).