Imagine two people trying to use two shared tools, but each holds one tool and waits for the other to release the second tool. What does this situation represent in databases?
Think about what happens when two processes wait forever for resources held by each other.
A deadlock occurs when two or more transactions hold locks that the others need, causing them to wait forever unless the system intervenes.
PostgreSQL provides system views to monitor locks and deadlocks. Which query correctly lists current deadlocks?
Look for locks that are waiting and relate them to processes waiting on locks.
Option B combines waiting locks with processes waiting on locks, helping identify deadlocks.
Two transactions lock tables in different orders causing deadlocks. Which code block correctly locks tables in the same order to prevent deadlocks?
Consistent locking order means all transactions lock tables in the same sequence and mode.
Option C locks 'orders' then 'customers' both in EXCLUSIVE MODE, ensuring consistent order and preventing deadlocks.
In a busy database, deadlocks happen often. Which approach best reduces deadlock frequency?
Think about how transaction length and lock order affect waiting.
Short transactions reduce lock time, and consistent lock order prevents circular waits, both reducing deadlocks.
Two transactions run concurrently:
Transaction 1:
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;
Transaction 2:
BEGIN;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
COMMIT;
What error will occur if both run at the same time?
Think about what happens when two transactions lock rows in opposite order.
Both transactions try to lock rows in opposite order causing a deadlock, so PostgreSQL aborts one with a deadlock error.