title: How to avoid database deadlocks?
body: <p>Some database features, such as <code>SELECT ... FOR UPDATE</code> and <code>ON DELETE CASCADE</code>, are implicitly vulnerable to deadlocks because the database does not specify what locking order will be used. I found <a href="http://hoopercharles.wordpress.com/2011/11/21/select-for-update-in-what-order-are-the-rows-locked/" rel="nofollow">two</a> <a href="https://groups.google.com/d/topic/h2-database/RYKQ1hLUqcg/discussion" rel="nofollow">discussions</a> that hint that this behavior isn't specified by the SQL standard, not to mention specific implementations. As such, I'm operating under the assumption that we cannot control the locking order (at least, it's not obvious how to do so).</p>
  
  <p><strong>How are we supposed to avoid database deadlocks if we cannot rely on the locking order?</strong></p>
  
  <p>If we're not supposed to avoid deadlocks (you're going to have to fight very hard to convince me of this) then what are we supposed to do?</p>
  
  <p>This question is meant to be database-agnostic so please don't ask me which database I'm using.</p>