Lesson 13 โ€ข Expert

    Transactions & ACID

    Guarantee data integrity with transactions โ€” the mechanism that prevents data corruption in every serious application.

    ๐ŸŽฏ What You'll Learn

    • BEGIN, COMMIT, and ROLLBACK
    • ACID properties: Atomicity, Consistency, Isolation, Durability
    • SAVEPOINTs for partial rollback
    • Isolation levels and concurrency control

    What Are Transactions?

    A transaction groups multiple SQL statements into one atomic operation. Either all statements succeed (COMMIT) or all are undone (ROLLBACK). No half-finished states.

    ๐Ÿฆ Real-World Analogy

    A bank transfer moves $500 from Account A to Account B. This requires two updates: subtract from A, add to B. If the system crashes after subtracting but before adding โ€” $500 vanishes! Transactions prevent this: both updates happen, or neither does.

    Basic Transactions

    Wrap multiple operations in BEGIN/COMMIT for safety

    Try it Yourself ยป
    SQL
    -- Basic transaction: bank transfer
    BEGIN TRANSACTION;
    
    -- Debit sender
    UPDATE accounts SET balance = balance - 500
    WHERE account_id = 1001;
    
    -- Credit receiver
    UPDATE accounts SET balance = balance + 500
    WHERE account_id = 1002;
    
    -- Both succeed or both fail โ€” that's atomicity!
    COMMIT;
    
    -- If something goes wrong:
    -- ROLLBACK;  -- undoes everything since BEGIN

    ACID Properties

    ๐Ÿ”’ Atomicity โ€” "All or Nothing"

    Every statement in the transaction succeeds, or everything is rolled back. No partial updates.

    โœ… Consistency โ€” "Rules Are Enforced"

    The database moves from one valid state to another. Constraints, foreign keys, and triggers are all respected.

    ๐Ÿ”€ Isolation โ€” "Transactions Don't Interfere"

    Concurrent transactions behave as if they ran one at a time. Your transaction doesn't see another's uncommitted changes.

    ๐Ÿ’พ Durability โ€” "Commits Are Permanent"

    Once committed, data survives power outages, crashes, and hardware failures. It's written to disk.

    Transaction with Error Handling

    Handle failures gracefully within a transaction

    Try it Yourself ยป
    SQL
    -- Transaction with error handling (PostgreSQL)
    BEGIN;
    
    -- Step 1: Create a new order
    INSERT INTO orders (customer_id, order_date, total)
    VALUES (42, CURRENT_DATE, 299.99);
    
    -- Step 2: Update inventory
    UPDATE products SET stock = stock - 1
    WHERE product_id = 101 AND stock > 0;
    
    -- Step 3: Check if inventory was available
    -- If no rows updated, stock was 0 โ†’ rollback
    -- In application code:
    -- if (rows_affected == 0) ROLLBACK;
    -- else COMMIT;
    
    COMMIT;

    SAVEPOINTs

    Partially roll back within a transaction

    Try it Yourself ยป
    SQL
    -- SAVEPOINT: partial rollback within a transaction
    BEGIN TRANSACTION;
    
    INSERT INTO orders (customer_id, total)
    VALUES (1, 100.00);
    
    SAVEPOINT after_order;
    
    INSERT INTO order_items (order_id, product_id, qty)
    VALUES (LAST_INSERT_ID(), 999, 1);
    -- Oops, product 999 doesn't exist!
    
    ROLLBACK TO SAVEPOINT after_order;
    -- Order is still saved, only the item is undone
    
    INSERT INTO order_items (order_id, product_id, qty)
    VALUES (LAST_INSERT_ID(), 101, 1);
    -- This product exists โ€” success!
    
    COMMIT;

    Isolation Levels

    Isolation levels control what one transaction can see while another is running:

    LevelDirty ReadNon-RepeatablePhantom
    READ UNCOMMITTEDโœ… Yesโœ… Yesโœ… Yes
    READ COMMITTEDโŒ Noโœ… Yesโœ… Yes
    REPEATABLE READโŒ NoโŒ Noโœ… Yes
    SERIALIZABLEโŒ NoโŒ NoโŒ No

    ๐Ÿ’ก Pro Tip

    READ COMMITTED is the default and sufficient for most applications. Only use SERIALIZABLE when you absolutely need it โ€” it's slower due to locking.

    Isolation Levels

    Control concurrency behavior between transactions

    Try it Yourself ยป
    SQL
    -- Isolation levels control what concurrent
    -- transactions can see
    
    -- READ UNCOMMITTED: see uncommitted changes (dirty reads)
    SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
    
    -- READ COMMITTED: only see committed data (default in most DBs)
    SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
    
    -- REPEATABLE READ: same query returns same results
    SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;
    
    -- SERIALIZABLE: strictest โ€” transactions run as if sequential
    SET TRANSACTION ISOLATION LEVEL SERIALIZAB
    ...

    ๐Ÿ“˜ Quick Reference

    CommandPurpose
    BEGIN / START TRANSACTIONStart a transaction
    COMMITSave all changes permanently
    ROLLBACKUndo all changes since BEGIN
    SAVEPOINT nameCreate a checkpoint
    ROLLBACK TO SAVEPOINT nameUndo to checkpoint

    ๐ŸŽ‰ Lesson Complete!

    You now understand transactions and ACID โ€” critical for building reliable applications. Next, you'll master advanced queries with window functions and CTEs!

    Sign up for free to track which lessons you've completed and get learning reminders.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy Policy โ€ข Terms of Service