title: IF block executes when the condition does not apply
body: <p>I have the following <code>IF</code> block that is supposed to be executed only if my table is empty. But it seems to be executing the code between <code>BEGIN</code> and <code>END</code> even when my table has a row.</p>
  
  <pre><code>IF ((SELECT COUNT(*) FROM [dbo].[KeyProperties]) = 0)
  BEGIN
      INSERT INTO [dbo].[KeyProperties] (KeyId,PropertyId) VALUES
      ((SELECT Id FROM [dbo].[Keys] WHERE Priority=1),(SELECT Id FROM [dbo].[Properties] WHERE Name='SocialSecurityNumber'))
      INSERT INTO [dbo].[KeyProperties] (KeyId,PropertyId) VALUES
      ((SELECT Id FROM [dbo].[Keys] WHERE Priority=2),(SELECT Id FROM [dbo].[Properties] WHERE Name='FirstName')),
      ((SELECT Id FROM [dbo].[Keys] WHERE Priority=2),(SELECT Id FROM [dbo].[Properties] WHERE Name='LastName')),
      ((SELECT Id FROM [dbo].[Keys] WHERE Priority=2),(SELECT Id FROM [dbo].[Properties] WHERE Name='Email'))
  END
  </code></pre>
  
  <p>The above code throws this error:</p>
  
  <blockquote>
    <p>Cannot insert the value NULL into column 'KeyId', table
    'MYDATABASE.dbo.KeyProperties'; column does not allow nulls. INSERT
    fails. The statement has been terminated. End</p>
  </blockquote>