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
create table credits (
int id,
int creds,
int user_id
);
The intent is to store some kind of credits for a user, e.g. something like stackoverflow's reputation.
How to deal with concurrent updates to that table ? A few options:
update credits set creds= 150 where userid = 1;
In this case the application retreived the current value, calculated the new value(150) and performed an update. Which spells disaster if someone else does the same at the same time. I'm guessing wrapping the retreival of the current value and update in a transaction would solve that , e.g.
Begin; select creds from credits where userid=1; do application logic to calculate new value, update credits set credits = 160 where userid = 1; end;
In this case you could check if the new credit would be < 0 and just truncate it to 0 if negative credits make no sense.update credits set creds = creds - 150 where userid=1;
This case wouldn't need to worry about concurrent updates as the DB takes care of the consistency problem, but has the flaw that creds would happily become negative, which might not make sense for some applications.
So simply, what's the accepted method to deal with the (quite simple) problem outlined above, what if the db throws an error ?