Is the AND
operator in SQL Server equivalent to &&
or &
in C# (or other languages)?
Ie, will it check for second condition if first condition is found to be false?
Is the AND
operator in SQL Server equivalent to &&
or &
in C# (or other languages)?
Ie, will it check for second condition if first condition is found to be false?
No, there is no short-circuiting in SQL. For example:
SELECT a, b, c
From T t
WHERE is_numeric(c) = 1 AND cast(c as numeric(10,2)) > 100.00
This may generate an invalid cast error where c is not numeric.
However you can force it to short-circuit by re-writing to use a CASE statement:
SELECT a, b, c
From T t
where
case
when is_numeric(c) = 0 then 0
when cast(c as numeric(10,2)) > 100.00 then 1
else 0
end = 1
In general and with the exception of handling nulls any clause of the form
where <EXPR1> AND <EXPR2> AND <EXP3>
can be written as:
where case
when NOT <EXPR1> then 0
when NOT <EXPR2> then 0
when NOT <EXPR3> then 0
else 1 end = 1
Any expression of the form:
where <EXPR1> OR <EXPR2> OR <EXPR3>
Can be written as:
where case
when <EXPR1> then 1
when <EXPR2> then 1
when <EXPR3> then 1
else 0 end = 1