Hacker News new | ask | show | jobs
by karmakaze 971 days ago
When it comes to row locks, there isn't a same time. Which row gets locked first if left unspecified can lead to deadlocks. All I was suggesting was:

  select balance from accounts where name = 'A' for update
  select balance from accounts where name = 'B' for update
where the two statements are run with smaller 'name' first, or

  select balance from accounts where name = 'A' or name = ‘B’ order by name for update
Of course, I'd use the primary key (likely an id rather than name).

By locking the accounts in smallest->largest name (or id), you can afford to do 2 separate for update calls. Even when done in a single statement specify the canonical ordering of locks to avoid deadlocks. For example, 3 transactions locking (A, B), (B, C), (C, A):

  tx1: lock A, lock B
  tx2: lock B, lock C
  tx3: lock A, lock C
This is the lock order regardless of which of A/B/C is being debited or credited. As a final detail, make sure the ORDER BY that you specify is on a unique index or else there could/will be range locks on the index and won't strictly be using row locks.