INSERT INTO T1 (xField) SELECT 7 AS xField WHERE (SELECT COUNT(*) FROM T1) = 0
Basically, if a million users all start this at the same time, can there ever be more than one line in T1?
Thread A: SELECT COUNT(*) FROM T1: 0 Thread B: SELECT COUNT(*) FROM T1: 0 Thread A: INSERT INTO T1... Thread B: INSERT INTO T1...
Or is it guaranteed to never happen, because this is all one statement?
If this is unsafe, how about this?
Table T2 (GoNorth and GoSouth should never be 1):
ID GoNorth GoSouth 1 0 0
Then this happens:
User A: UPDATE T2 SET GoNorth = 1 WHERE GoSouth = 0 User B: UPDATE T2 SET GoSouth = 1 WHERE GoNorth = 0 Thread A: Find rows where GoSouth = 0 Thread B: Find rows where GoNorth = 0 Thread A: Found a row where GoSouth = 0 Thread B: Found a row where GoNorth = 0 Thread A: Setting GoNorth = 1 for the located row Thread B: Setting GoSouth = 1 for the located row
And the result:
ID GoNorth GoSouth 1 1 1
What are the rules for what can happen at the same time and what cannot?
My database engine is "Microsoft SQL Server 2008 R2 (SP2)."
source share