INSERT INTO T1 (xField) SELECT 7 AS xField WHERE (SELECT COUNT(*) FROM T1) = 0
Basically, if a million users all run this at the same time, could there ever end up being more than one row 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 that guaranteed to never happen, because it's all one statement?
If that isn't safe, what about something like this?
Table T2 (GoNorth and GoSouth must never both 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 can't?
My database engine is "Microsoft SQL Server 2008 R2 (SP2)".