Skip to content

Instantly share code, notes, and snippets.

@andrewyatz
Created March 1, 2011 18:29
How to deadlock MySQL
-- Setup the following schema
CREATE TABLE `seq` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(11) NOT NULL,
`value` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name_idx` (`name`)
) ENGINE=InnoDB;
-- In process 1
set autocommit = 0;
select * from seq where name = 'foo' for update;
-- In process 2
set autocommit = 0;
select * from seq where name = 'foo' for update;
-- In process 1
insert into seq (name, value) values ('foo', 1);
-- process 1 will now block
-- In process 2
insert into seq (name, value) values ('foo', 1);
-- Process 2 will deadlock & will allow process 1 to continue
@andrewyatz
Copy link
Author

This is meant to describe why you encounter deadlocks sometimes when you don't expect to

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment