Introduction
Read phenomena happen when database transactions see data changes in unexpected ways. Understanding them helps keep data correct and reliable.
-- No specific syntax, but these phenomena happen during transactions BEGIN TRANSACTION; -- Read or write queries here COMMIT;
-- Dirty Read example -- Transaction 1 updates a row but does not commit BEGIN TRANSACTION; UPDATE accounts SET balance = 500 WHERE id = 1; -- Transaction 2 reads the updated balance before commit SELECT balance FROM accounts WHERE id = 1; -- If Transaction 1 rolls back, Transaction 2 read wrong data (dirty read)
-- Phantom Read example -- Transaction 1 reads rows matching a condition BEGIN TRANSACTION; SELECT * FROM orders WHERE status = 'pending'; -- Transaction 2 inserts a new 'pending' order and commits BEGIN TRANSACTION; INSERT INTO orders (id, status) VALUES (101, 'pending'); COMMIT; -- Transaction 1 reads again and sees new row (phantom)
-- Setup sample table CREATE TABLE products (id INT PRIMARY KEY, name VARCHAR(20), price INT); INSERT INTO products VALUES (1, 'Pen', 10), (2, 'Book', 20); -- Transaction 1 starts BEGIN TRANSACTION; UPDATE products SET price = 15 WHERE id = 1; -- Transaction 2 reads before Transaction 1 commits SELECT price FROM products WHERE id = 1; -- Transaction 1 rolls back ROLLBACK;
dirty read in database transactions?dirty reads?Orders. Transaction 1 reads all rows where status = 'pending'. Transaction 2 inserts a new row with status = 'pending' and commits. If Transaction 1 repeats the read, what phenomenon might it observe?BEGIN TRANSACTION;
SELECT * FROM Products WHERE price > 100;
-- Another transaction inserts a new product with price 150 and commits
SELECT * FROM Products WHERE price > 100;
COMMIT;
Pass the test and this pattern moves unknown