I’m getting the following error pretty often when running a certain query in my database (all tables use the InnoDB storage engine): “Deadlock found when trying to get lock; try restarting transaction”
The query is DELETE FROM sessions WHERE userid != 0 AND lastactivity < 1289594761 AND admin = 1 AND userid NOT IN (SELECT userid FROM users WHERE (userflags & 1048576))
The errors started to occur when I’ve added the NOT IN part to my WHERE statement.
Why is this causing issues and what can I do to prevent this?
An easy solution would be to separate this into two consecutive queries. I.e.,:
SELECT userid into #tmptable FROM users WHERE (userflags & 1048576);
DELETE FROM sessions WHERE userid != 0 AND lastactivity < 1289594761 AND admin = 1 AND userid NOT IN (select userid from #tmptable);
That way you’re working with a local session copy of the values from the second table and not causing a read lock on it. However, this is just a quick-and-dirty solution. A better solution would be to analyze the transaction lock settings from all activities that touch these two tables and to rewrite the query, if you’ll be re-using it regularly.