How can I Cause a Deadlock in MySQL for Testing Purposes How can I Cause a Deadlock in MySQL for Testing Purposes database database

How can I Cause a Deadlock in MySQL for Testing Purposes


Here's some pseudocode for how i do it in PHP:

Script 1:

START TRANSACTION;INSERT INTO table <anything you want>;SLEEP(5);UPDATE table SET field = 'foo';COMMIT;

Script 2:

START TRANSACTION;UPDATE table SET field = 'foo';SLEEP(5);INSERT INTO table <anything you want>;COMMIT;

Execute script 1 and then immediately execute script 2 in another terminal. You'll get a deadlock if the database table already has some data in it (In other words, it starts deadlocking after the second time you try this).

Note that if mysql won't honor the SLEEP() command, use Python's equivalent in the application itself.


you can always run LOCK TABLE tablename from another session (mysql CLI for instance). That might do the trick.

It will remain locked until you release it or disconnect the session.


I'm not familar with Python, so excuse my incorrect language If I'm saying this wrong... but open two sessions (in separate windows, or from separate Python processes - from separate boxes would work ... ) Then ...

. In Session A:

   Begin Transaction       Insert TableA()  Values()... 

. Then In Session B:

Begin Transaction  Insert TableB() Values()...   Insert TableA() Values() ...

. Then go back to session A

  Insert TableB() Values () ...

You'll get a deadlock...