Introduction
Deadlocks happen when two or more tasks wait for each other to finish, causing a standstill. Understanding and preventing deadlocks helps keep databases running smoothly without freezing.
-- No single syntax for deadlock, but prevention techniques include: -- 1. Access tables in the same order in all transactions -- 2. Keep transactions short -- 3. Use proper isolation levels -- 4. Use explicit locking carefully -- Example: Locking rows in a consistent order BEGIN TRANSACTION; SELECT * FROM accounts WHERE id = 1 FOR UPDATE; SELECT * FROM accounts WHERE id = 2 FOR UPDATE; -- perform updates COMMIT;
-- Example 1: Consistent locking order BEGIN TRANSACTION; SELECT * FROM accounts WHERE id = 1 FOR UPDATE; SELECT * FROM accounts WHERE id = 2 FOR UPDATE; -- update balances COMMIT;
-- Example 2: Avoid long transactions BEGIN TRANSACTION; -- quick update UPDATE accounts SET balance = balance + 100 WHERE id = 1; COMMIT;
-- Example 3: Use lower isolation level if possible SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
-- Simulate deadlock prevention by locking in consistent order BEGIN TRANSACTION; SELECT * FROM accounts WHERE id = 1 FOR UPDATE; SELECT * FROM accounts WHERE id = 2 FOR UPDATE; UPDATE accounts SET balance = balance - 50 WHERE id = 1; UPDATE accounts SET balance = balance + 50 WHERE id = 2; COMMIT;
Transaction 1: LOCK table A; LOCK table B;Transaction 2: LOCK table B; LOCK table A;Orders and Customers. Which approach is best?Customers first, then Orders, and keep transactions short enforces consistent order and short transactions, preventing deadlocks effectively.Customers first, then Orders, and keep transactions short -> Option APass the test and this pattern moves unknown