This module covers Transaction Control, ACID Properties, Isolation Levels, Deadlocks and Locking.
Transaction control in SQL allows you to manage database operations by grouping them into logical units of work, ensuring data consistency and integrity. This section covers the essential transaction control commands: `BEGIN`, `COMMIT`, `ROLLBACK`, and `SAVEPOINT`.
BEGIN;
-- Perform database operations
e.g. INSERT INTO users (name) VALUES ('John');
SAVEPOINT my_savepoint;
-- Potentially problematic operation
UPDATE accounts SET balance = balance - 100 WHERE user_id = 1;
ROLLBACK TO my_savepoint;
-- Try alternative approach
INSERT INTO transactions (amount, type) VALUES (100, 'debit');
COMMIT;
// Don't leave transactions open indefinitely
BEGIN;
-- Some operations
e.g. SELECT * FROM users; // This locks rows in some databases
// No commit or rollback issued -> leads to lock contention and database hang-ups
ACID properties are fundamental to ensuring data integrity in relational databases. ACID stands for **Atomicity**, **Consistency**, **Isolation**, and **Durability**.
Atomicity ensures that a database transaction is treated as a single unit of work. A transaction must either complete entirely or not happen at all.
START TRANSACTION;
UPDATE accounts SET balance = balance - 100 WHERE account_id = 123;
UPDATE accounts SET balance = balance + 100 WHERE account_id = 456;
COMMIT;
START TRANSACTION;
UPDATE accounts SET balance = 100 WHERE account_id = 123;
ROLLBACK;
Consistency ensures that a transaction never leaves the database in an inconsistent state. If a transaction is completed, all data remains valid and consistent.
CREATE TABLE orders (
order_id INT PRIMARY KEY,
product_id INT NOT NULL,
quantity INT CHECK (quantity > 0)
);
Isolation ensures that concurrent transactions are isolated from each other. The isolation level determines how transactions interact with each other.
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;
Durability ensures that once a transaction is committed, it remains in the database permanently. Even if there is a system crash or power failure.
COMMIT;
// Don't do this - long running transaction
START TRANSACTION;
... complex operations ...
SLEEP(10);
COMMIT;
When working with database transactions, **isolation levels** determine how transaction data is isolated from other transactions. SQL defines four standard isolation levels: **Read Uncommitted**, **Read Committed**, **Repeatable Read**, and **Serializable**. Understanding these levels is crucial for managing concurrency and preventing issues like **dirty reads**, **uncommitted reads**, and **phantom reads**.
### Dirty Reads, Uncommitted Reads, and Phantom Reads - **Dirty Read**: Reading uncommitted data that may be rolled back. - **Uncommitted Dependency**: Relying on data that might change before commit. - **Phantom Read**: New records appearing in a result set between transactions.
This level allows reading uncommitted data from other transactions. Use this when: - You need maximum concurrency and don't mind potential inconsistencies. - The data being read doesn't require consistency across transactions.
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
**Example**: Reading analytics data where occasional inconsistency is acceptable.
This level prevents dirty reads but allows other concurrency issues like **phantom reads** and **uncommitted dependencies**. It's a good balance between performance and consistency.
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
**Example**: E-commerce applications where orders should reflect committed data but don't need full isolation.
Ensures that all repeated queries within a transaction return the same results. Prevents **dirty reads**, **phantom reads**, and **uncommitted dependencies** except for updates by higher-level transactions.
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;
**Example**: Financial applications where consistency is critical but some concurrency is still needed.
This level ensures transactions are executed serially, one after another. Prevents all types of concurrency issues but can impact performance due to increased locking.
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
**Example**: Applications requiring strict consistency, like banking systems or inventory management.
// Example of setting isolation level in a transaction
BEGIN TRANSACTION;
SET ISOLATION LEVEL REPEATABLE READ;
**Scenario**: A banking application transferring funds between accounts. The transfer must be atomic and consistent.
In SQL, **transaction management** is crucial for maintaining data integrity and consistency. One of the most critical aspects of transaction management is handling concurrency control through locking mechanisms. This chapter explores the concepts of **optimistic locking**, **pessimistic locking**, and how to prevent **deadlocks** in database transactions.
**Optimistic locking** assumes that multiple transactions can complete without conflicting with each other. It allows concurrent modifications and only checks for conflicts when committing the transaction.
BEGIN TRANSACTION;
UPDATE orders SET status = 'completed' WHERE order_id = 100;
COMMIT;
**Pessimistic locking** assumes that conflicts are likely and places locks on resources as soon as they are accessed. This prevents other transactions from modifying the same data until the lock is released.
BEGIN TRANSACTION;
SELECT * FROM users WHERE id = 1 FOR UPDATE;
UPDATE users SET name = 'John' WHERE id = 1;
COMMIT;
A **deadlock** occurs when two or more transactions are waiting indefinitely for locks to be released by other transactions. This creates a situation where no transaction can proceed, leading to database unresponsiveness.
/* Example of a potential deadlock scenario */
-- Transaction 1
BEGIN TRANSACTION;
SELECT * FROM tableA WHERE id = 1 FOR UPDATE;
SELECT * FROM tableB WHERE id = 2 FOR UPDATE;
-- Transaction 2
BEGIN TRANSACTION;
SELECT * FROM tableB WHERE id = 2 FOR UPDATE;
SELECT * FROM tableA WHERE id = 1 FOR UPDATE;
Question 1 of 19