Skip to main content
SQL Fundamentals
CHAPTER 23 Beginner

SQL Transactions Explained | ACID Properties

Updated: May 16, 2026
15 min read

# 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. 1. UPDATE accounts SET balance = balance - 100 WHERE name = 'Alice';
  1. 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 COMMIT to permanently save data.
  • Execute a ROLLBACK to 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 NULL column to NULL). 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. 1. START TRANSACTION (or BEGIN in PostgreSQL): Turns off auto-save.
  1. 2. COMMIT: Tells the database to permanently save all the pending queries.
  1. 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.
sql
1234567891011
-- Step 1: Tell SQL to pause Auto-Saving!
START TRANSACTION;

-- Step 2: Deduct money from Alice (Pending state...)
UPDATE accounts SET balance = balance - 100 WHERE name = 'Alice';

-- Step 3: Add money to Bob (Pending state...)
UPDATE accounts SET balance = balance + 100 WHERE name = 'Bob';

-- Step 4: Both queries succeeded without server crashes! Make it permanent!
COMMIT;

*(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!
sql
1234567
START TRANSACTION;

-- Oh no! I forgot the WHERE clause!
DELETE FROM customers; 

-- Phew! Undo the mistake!
ROLLBACK;

*(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.
sql
12345678910111213
START TRANSACTION;

-- 1. Create the Order
INSERT INTO orders (user_id, total) VALUES (5, 120.00);

-- 2. Add the Items to the Receipt
INSERT INTO order_items (order_id, product_id, qty) VALUES (99, 10, 1);

-- 3. Reduce the physical inventory
UPDATE inventory SET stock = stock - 1 WHERE product_id = 10;

-- 4. If all 3 steps succeeded, lock it in!
COMMIT;

*(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 5 UPDATE queries, and then close your computer without running COMMIT, the database assumes you abandoned the transaction and automatically ROLLBACKs 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. 1. What does the "A" in ACID stand for, and what does it mathematically guarantee?
  1. 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 that UPDATEs an order status to 'Refunded', and then UPDATEs the customer's wallet balance by adding 50. End the block by permanently saving the changes.
sql
1234
START TRANSACTION;
UPDATE orders SET status = 'Refunded' WHERE id = 10;
UPDATE wallets SET balance = balance + 50 WHERE user_id = 5;
COMMIT;

12. MCQ Quiz with Answers

Question 1

In the context of Relational Databases, what is the fundamental purpose of the START TRANSACTION and COMMIT commands?

Question 2

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/catch error-handling block and the SQL COMMIT/ROLLBACK commands during a multi-table E-commerce checkout process.

14. FAQs

Q: Does ROLLBACK 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!).

15. Summary

You have unlocked enterprise-grade data security. By mastering Transactions and understanding the unbreakable laws of ACID properties, you can architect backend workflows for financial institutions, e-commerce giants, and any application where data corruption is absolutely unacceptable.

16. Next Chapter Recommendation

Right now, our Node.js or PHP server has to send 5 different SQL commands across the internet to execute a transaction. What if we could save that entire logic *inside* the database itself, and trigger it with a single command? In Chapter 24: Stored Procedures and Functions, we will learn how to write actual programming logic inside SQL.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·