Here is how to create deadlocks in PostgreSQL for testing purposes:

  1. Open 2 sessions logged in with the same account in PostgreSQL.

  2. 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 at 5min instead of 1h to keep it more reasonable.

  3. In Session 2, type the following:

    SET deadlock_timeout = '1h';
    BEGIN;
    SELECT * FROM users WHERE id = 200 FOR UPDATE:
    
  4. In Session 1, type the following:

    SELECT * FROM users WHERE id = 200 FOR UPDATE:
    

    A block occurs after trying to execute this query.

  5. In Session 2, type the following:

    SELECT * FROM users WHERE id = 100 FOR UPDATE:
    

    A block occurs after trying to execute this query.