OR Operator Short-circuit in SQL Server

NotTwoWayStreet picture NotTwoWayStreet · Jun 27, 2012 · Viewed 13.3k times · Source

I want to consult SQL Server OR short-circuit

Code:

   DECLARE @tempTable table
      (
         id int
      )
      INSERT @tempTable(id) values(1)

      DECLARE @id varchar(10)
      SET @id = 'x'
      SELECT * FROM @tempTable WHERE 1=1 OR id = @id --successfully
      SELECT * FROM @tempTable WHERE @id = 'x' OR id = @id --Exception not Convert 'x' to int

Why? 1=1 and @id='x' is true.

SQL Server OR operator : whether the short-circuit function?

THANKS

Answer

Steven Mastandrea picture Steven Mastandrea · Jun 27, 2012

Within SQL, there is no requirement that an OR clause breaks early. In other words, it is up to the optimizer whether to check both conditions simutaneously. I am not an expert in the MSSQL optimizer, but I have seen instances where the optimizer has and has not short circuited an OR clause.