Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do all parts of a SQL SERVER expression using 'OR' get evaluated?

Given:

WHERE (@Id Is NULL OR @Id = Table.Id)

If @Id is null: the expression evaluates to true. Does the second part @Id = Table.Id still get considered? or is it sufficient that the expression evaluates to true given that the first part is (which is the case in c#).

This is relevant because of some much more complex OR statements where it is important to know if all parts are getting evaluated.


UPDATE:

I have since found this syntax to be a good alternative

WHERE (Table.Id = ISNULL(@Id, Table.Id))
like image 782
CRice Avatar asked Nov 19 '09 05:11

CRice


People also ask

Does SQL evaluate and or or first?

SQL Server query operators OR and AND are commutative. There is no inherent order and the query optimizer is free to choose the path of least cost to begin evaluation. Once the plan is set, the other part is not evaluated if a result is pre-determined.

Does SQL CASE evaluate all conditions?

A CASE expression evaluates to the first true condition. If there is no true condition, it evaluates to the ELSE part. If there is no true condition and no ELSE part, it evaluates to NULL .

Which expression should be evaluated next in SQL?

Within an expression, higher precedence operators will be evaluated first. The precedence of operators goes as follows: =, <, >, <=, >=, <>, != , ~=, ^=, IS NULL, LIKE, BETWEEN, IN.

How does SQL evaluate or statements?

The SQL Server OR is a logical operator that allows you to combine two Boolean expressions. It returns TRUE when either of the conditions evaluates to TRUE . In this syntax, the boolean_expression is any valid Boolean expression that evaluates to true, false, and unknown.


2 Answers

Sometimes they are, sometimes they aren't. SQL Server does not guarantee boolean operator short circuit, don't rely on it for correctness. See this blog entry: Boolean Operator Short Circuit.

Complex queries that depend on @variables like this are much better written as explicit IF statements:

IF (@id IS NULL)
  SELECT ... FROM ... WHERE ...
ELSE
  SELECT ... FROM ... WHERE ...
like image 90
Remus Rusanu Avatar answered Sep 21 '22 03:09

Remus Rusanu


Execution plans may not be so great with a query like that. Both will be evaluated.

like image 35
JonH Avatar answered Sep 18 '22 03:09

JonH