The single-step answer to the first question is to use something like:
update TBL set CLM = CLM + 1 where key = 'KEY'
That's very much a single-instruction way of doing it.
As for the second question, you shouldn't need to resort to DBMS-specific SQL gymnastics (like UPSERT
) to get the result you want. There's a standard method to do update-or-insert that doesn't require a specific DBMS.
try:
insert into TBL (key,val) values ('xyz',0)
catch:
do nothing
update TBL set val = val + 1 where key = 'xyz'
That is, you try to do the creation first. If it's already there, ignore the error. Otherwise you create it with a 0 value.
Then do the update which will work correctly whether or not:
- the row originally existed.
- someone updated it between your insert and update.
It's not a single instruction and yet, surprisingly enough, it's how we've been doing it successfully for a long long time.