What\'s the common way to deal with concurrent updates in an SQL database ?
Consider a simple SQL schema(constraints and defaults not shown..) like
c
For MySQL InnoDB tables, this really depends on the isolation level you set.
If you are using the default level 3 (REPEATABLE READ), then you would need to lock any row that affects subsequent writes, even if you are in a transaction. In your example you will need to :
SELECT FOR UPDATE creds FROM credits WHERE userid = 1;
-- calculate --
UPDATE credits SET creds = 150 WHERE userid = 1;
If you are using level 4 (SERIALIZABLE), then a simple SELECT followed by update is sufficient. Level 4 in InnoDB is implemented by read-locking every row that you read.
SELECT creds FROM credits WHERE userid = 1;
-- calculate --
UPDATE credits SET creds = 150 WHERE userid = 1;
However in this specific example, since the computation (adding credits) is simple enough to be done in SQL, a simple:
UPDATE credits set creds = creds - 150 where userid=1;
will be equivalent to a SELECT FOR UPDATE followed by UPDATE.