Transactions and ACID Properties
# CHAPTER 20
Transactions and ACID Properties
1. Introduction
Imagine you are building a banking application. John transfers $500 to Sarah. The backend code executes two SQL queries:-
1.
UPDATE accounts SET balance = balance - 500 WHERE name = 'John';
-
2.
UPDATE accounts SET balance = balance + 500 WHERE name = 'Sarah';
What happens if the database server loses power in the microsecond *after* query 1 finishes, but *before* query 2 runs? John's $500 is gone forever, and Sarah never receives it. The data is fatally corrupted. To prevent this, relational databases use Transactions. In this chapter, we will learn how to group multiple queries into unbreakable "all-or-nothing" operations.
2. Learning Objectives
By the end of this chapter, you will be able to:- Explain the four pillars of ACID compliance.
-
Start a manual Transaction using
BEGIN.
-
Save a Transaction to the hard drive using
COMMIT.
-
Abort and undo a Transaction using
ROLLBACK.
-
Utilize
SAVEPOINTfor partial rollbacks.
3. What is ACID Compliance?
PostgreSQL is renowned for being strictly ACID compliant. ACID is an acronym representing the gold standard of database reliability:- A (Atomicity): "All or nothing." If a transaction has 5 queries, and query 5 fails, queries 1-4 are instantly undone.
-
C (Consistency): Data must always meet all Constraints (like the
CHECKconstraints we built in Chapter 19).
- I (Isolation): If 1,000 users are transferring money at the exact same millisecond, their transactions operate in isolation and do not overlap or read each other's half-finished math.
- D (Durability): Once PostgreSQL replies "Success" (Committed), the data is permanently saved to the physical hard drive. Even if you pull the power plug 0.1 seconds later, the data survives.
4. Anatomy of a Transaction
By default, every singleINSERT or UPDATE you type is its own micro-transaction. It automatically commits.
To group multiple queries together, you must manually open a transaction block using the BEGIN command.
*(If the power fails before COMMIT is executed, PostgreSQL will automatically erase the entire transaction upon reboot).*
5. Time Travel with ROLLBACK
If you are inside a BEGIN block, and you realize you made a catastrophic mistake (like forgetting a WHERE clause on a DELETE statement), you do NOT type COMMIT.
You type ROLLBACK. This acts as a massive "Undo" button, instantly reverting the database to the exact state it was in before you typed BEGIN.
6. Using Savepoints
Transactions can be massive. If you execute 100 queries inside aBEGIN block, and query 101 fails, ROLLBACK undoes all 100 successful queries.
To prevent this, you can drop SAVEPOINT flags inside the transaction. Think of them as video game checkpoints.
7. Concurrency and Locks (Why PostgreSQL is Amazing)
If John is updating his profile (inside an open transaction), and Sarah tries to read John's profile at the exact same moment, what does Sarah see? PostgreSQL uses MVCC (Multi-Version Concurrency Control). Unlike older databases that would "lock" the table and make Sarah wait, PostgreSQL takes a snapshot. Sarah sees the *old* version of John's profile instantly, without waiting. Once John hitsCOMMIT, the old version is deleted and the new version becomes reality. "Readers never block writers, and writers never block readers."
8. Mini Project: The E-Commerce Checkout
A complex checkout operation MUST be wrapped in a transaction. Let's draft the logic.9. Common Mistakes
-
Forgetting to COMMIT: If you type
BEGIN;, run anUPDATE, and close your terminal window without typingCOMMIT;, PostgreSQL assumes the connection was severed and automatically executes aROLLBACK. The update will be lost!
-
Long-Running Transactions: Never leave a
BEGINblock open while waiting for user input. It consumes database resources and can cause internal locks. Transactions should execute in milliseconds.
10. Best Practices
-
Let the Backend handle it: In modern web development, you rarely type
BEGIN;manually. Your ORM framework (like Laravel's Eloquent or Node's Prisma) handles theBEGINandCOMMITautomatically under the hood when you use their Transaction helper functions.
11. Exercises
- 1. What does the "A" in ACID stand for, and what does it mean?
- 2. Write the command to manually abort an open transaction block.
12. SQL Challenges
You are inside aBEGIN; block. You update an employee's salary. You suddenly realize it was the wrong employee. You have NOT typed COMMIT yet. What exact command do you type to revert the change?
13. MCQ Quiz with Answers
In the context of ACID properties, what does "Atomicity" guarantee?
What happens if a server physically loses power while a massive UPDATE query is actively running inside a BEGIN transaction, but before COMMIT is reached?
14. Interview Questions
- Q: Explain the four ACID properties (Atomicity, Consistency, Isolation, Durability) and why they are the foundational requirement for a financial database.
- Q: Describe PostgreSQL's MVCC (Multi-Version Concurrency Control) architecture. How does it handle a situation where User A is reading a row while User B is actively updating that exact same row?
15. FAQs
Q: Does MySQL support Transactions? A: Yes, modern MySQL (using the InnoDB engine) supports Transactions and ACID compliance, though historically, PostgreSQL has possessed a much stricter and more robust implementation of these features.16. Summary
Transactions are your ultimate safety net against chaos. By understanding ACID principles and wrapping critical multi-step logic insideBEGIN and COMMIT blocks, you guarantee that power failures, server crashes, and runtime code errors will never result in corrupted, half-finished data states.