Here is how to create deadlocks in PostgreSQL for testing purposes:
-
Open 2 sessions logged in with the same account in PostgreSQL.
-
In session 1, type the following:
SET deadlock_timeout = '1h'; BEGIN; SELECT * FROM users WHERE id = 100 FOR UPDATE:NOTE: The default deadlock_timeout is
1s. You can also set it at5mininstead of1hto keep it more reasonable. -
In Session 2, type the following:
SET deadlock_timeout = '1h'; BEGIN; SELECT * FROM users WHERE id = 200 FOR UPDATE: -
In Session 1, type the following:
SELECT * FROM users WHERE id = 200 FOR UPDATE:A block occurs after trying to execute this query.
-
In Session 2, type the following:
SELECT * FROM users WHERE id = 100 FOR UPDATE:A block occurs after trying to execute this query.