SQL Transactions Practice Guide

Understanding the Problem

We need to understand and work with SQL transactions in three scenarios:

Devising a Plan

  1. Analyze transaction flow in each scenario
  2. Track balance changes and rollback effects
  3. Understand transaction isolation
  4. Implement constraint violation handling

Part 1: Understanding Rollbacks

Initial Table State

| id | first_name | last_name | balance |
|----|------------|-----------|----------|
| 1  | Amy        | Pond      | 2500    |
| 2  | Rose       | Tyler     | 600     |
| 3  | Martha     | Jones     | 3000    |
| 4  | Donna      | Noble     | 200     |
| 5  | River      | Song      | 1200    |

Transaction Analysis

Let's analyze the transactions in 01-transactions-rollbacks.sql step by step:

  1. Amy to Rose: 200
  2. Martha to Rose: 200
  3. Donna to Rose attempt (rolled back):
  4. River to Rose: 200

Final Expected Balances

| id | first_name | last_name | balance |
|----|------------|-----------|----------|
| 1  | Amy        | Pond      | 2300    |
| 2  | Rose       | Tyler     | 1200    |
| 3  | Martha     | Jones     | 2800    |
| 4  | Donna      | Noble     | 200     |
| 5  | River      | Song      | 1000    |

Part 2: Connection Interrupts

Understanding Connection Behavior

When a connection is interrupted during a transaction:

Testing Connection Interrupts

-- In first terminal:
.read 02-transactions-connection-interrupt.sql
SELECT * FROM accounts;  -- Shows partial transaction state

-- In second terminal:
SELECT * FROM accounts;  -- Shows original state

-- After closing first terminal:
SELECT * FROM accounts;  -- Shows original state (auto-rollback)

Part 3: Constraint Violations

Original File (No Rollback)

BEGIN TRANSACTION;
  UPDATE accounts
  SET balance = balance + 1000
  WHERE (first_name = 'Amy' AND last_name = 'Pond');

  UPDATE accounts
  SET balance = balance - 1000
  WHERE (first_name = 'Rose' AND last_name = 'Tyler');
COMMIT;

Modified File (With Rollback)

BEGIN TRANSACTION;
  UPDATE accounts
  SET balance = balance + 1000
  WHERE (first_name = 'Amy' AND last_name = 'Pond');

  UPDATE OR ROLLBACK accounts
  SET balance = balance - 1000
  WHERE (first_name = 'Rose' AND last_name = 'Tyler');
COMMIT;

Key Concepts

SAVEPOINT

SAVEPOINTs are like checkpoints in your transaction that you can return to:

ROLLBACK

ROLLBACK can be used in two ways:

OR ROLLBACK Clause

Adding OR ROLLBACK to updates:

Common Mistakes to Avoid

Best Practices