There are two tables:

Table 1 Unique Sessions

ID    Count 

Table 2 (Sessions)

ID    Name

I would like to update count only if name does not exist into sessions to count unique sessions, this is an example so objective is not to do it by alternative way, but question is:

Rowsaffected = Update table1 
                   set Count = Count + 1 
               where (Select count(*) from table2 where Name = 'user1' ) = 0;

Insert into table2 (NAME) values('user');

Is first query an atomic query ? If yes, then there is no issue.

If no, then What if there are multiple threads running to perform above mentioned operations ? There is a chance that:

Thread 1: count returns 0, it has updated table 1 but not table 2 before Thread 2 starts. Thread 2: It finds count 0, it is also going to update count.

Now for same user, count is 2 which shouldn't happen.

Any suggestion / feedback.

Edit
Report