title: SQL Server 2012 potential race condition on select or insert
body: <p>I need to run a SQL Server query that either "gets" or "creates" a record. Pretty simple, but I am  not sure if this will create any race conditions. </p>
  
  <p>I have read a few articles regarding locking  during insert/updates e.g. <a href="http://weblogs.sqlteam.com/dang/archive/2007/10/28/Conditional-INSERTUPDATE-Race-Condition.aspx" rel="nofollow">http://weblogs.sqlteam.com/dang/archive/2007/10/28/Conditional-INSERTUPDATE-Race-Condition.aspx</a>, but I'm not sure if this is relevant to me given I'm using SQL Server 2012, and I don't have contention over modification per se, only over ensuring 'one off creation' of my record. </p>
  
  <p>Also, I will have a primary key constraint over the <code>Id</code> column (not an identity column), so I know the race condition at worst could only ever create an error, and not invalid data, but I also don't want the command to throw an error.</p>
  
  <p>Can someone please shed some light on how I need to solve this? Or am I over thinking this and can I simply do something like:</p>
  
  <pre><code>IF EXISTS(SELECT * FROM Table WHERE Id = @Id)
  BEGIN
        SELECT Id, X, Y, Z FROM Table WHERE Id = @Id
  END
  ELSE
  BEGIN
        INSERT INTO Table (Id, X, Y, Z)
        VALUES (@Id, @X, @Y, @Z);
  
        SELECT @Id, @x, @Y, @Z;
  END
  </code></pre>
  
  <p>I've been in document database land for a few years and my SQL is very rusty.</p>