When implementing database queries I'm often wondering if the query I'm writing can potentially deadlock when executed in parallel by many clients. Often I only find out by running the query in parallel with a large number of clients to see if I'm getting the infamous "deadlock detected" in practice.
I'm wondering if there is a more formal approach to determine if a query has the potential to deadlock? By "more formal" I mean something like:
- Is it possible to inspect/explain what the query is doing under the hood even when executed in isolation and judge from e.g. some internal logs that a deadlock is possible? If I could for instance see the exact locks that are needed and their order, I could probably predict if it can deadlock. In practice, I often just don't know if the query is locking on table or on row level. In such a case the assumption would be e.g. that a single table lock is fine, but locking multiple rows non-atomically brings the deadlock potential, because another instance of the query could lock the rows in a different order.
- If it isn't possible via inspecting logs, are there some general patterns to look for in queries that are a potential deadlock?