How does SQL Server evaluate an OR operator?


I would like to know if, under SQL Server 2012 , an A OR B , when evaluating the veracity of A returns true as a result of the OR without the need to evaluate B


I understand that the reason for your question is not that you do not understand what the result of the OR operator is, but that you want to know if SQL Server takes the pain of evaluating the second condition if the result can be determined by evaluating the first only.

And I imagine the question arises because other languages ​​like C # or Java have that optimization known as short-circuit evaluation .

For SQL Server, and other databases, the answer is the same: the database engine also has the ability to perform short-circuit evaluation , that is, not to evaluate the second condition if it is not necessary. But there is no guarantee that you will always do it that way.

Actually, it is always good to remember that, contrary to other languages ​​such as C # or Java, the SQL language is a declarative language that limits itself to defining which result we want, but does not impose how to obtain it. So the database engine has the right to change the SQL and the way it evaluates conditions however it wants, as long as the result is the same.

For example, if your condition is A or B The database engine has the right to modify the condition to B or A , so you cannot assume that B will not be evaluated. The behavior may vary depending on the circumstances.

Links of interest that treat the subject with more details and examples to demonstrate that there are no guarantees:

Especially that last reference, I recommend reading it. Here I have translated part of what he mentions:

Several developers who are used to imperative languages ​​like C assume that short-circuited Boolean evaluation is used when executing SQL queries.

SQL is a declarative language. The optimizer has the right to choose any execution plan that provides the desired result. Short-circuited evaluation of Boolean operators IS NOT GUARANTEED.

Scroll to Top