Search code examples
sql-servert-sqlquery-optimizationshort-circuiting

OR Operator Short-circuit in SQL Server


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' are true.

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

THANKS


Solution

  • 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.