- Open two connections in parallel, like two
psql instances or two query windows in pgAdmin (each has its own session). - Start a transaction on each connection.
BEGIN; - Execute mutually conflicting commands in turn.
- Before you can commit, one of the two will be rolled back with the exception of the deadlock.
- You can roll back another.
ROLLBACK;
Explicitly locking tables is as simple as:
LOCK tbl;
String locking can be done with:
SELECT * FROM tbl WHERE boo = 3 FOR UPDATE;
Or FOR SHARE , etc. Details in the manual here.
example
Your added example cannot be deadlocked. Both try to first take the same lock on the same row of the same table. The second will wait for the first to finish.
Example for creating a dead end (rows must exist or no lock will be taken):
Transaction 1 Transaction 2 BEGIN; BEGIN; SELECT salary1 FROM deadlock_demonstration WHERE worker_id = 1 FOR UPDATE; SELECT salary1 FROM deadlock_demonstration WHERE worker_id = 2 FOR UPDATE; UPDATE deadlock_demonstration SET salary1 = 100 WHERE worker_id = 2; UPDATE deadlock_demonstration SET salary1 = 100 WHERE worker_id = 1; ... deadlock!
Result
OP user3388473 provided this screenshot after checking my solution:

source share