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

2

8

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))
Eastbound answered 19/11, 2009 at 5:10 Comment(1)
In complicated queries both sides might be run in parallel...Topside
E
11

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 ...
Eagan answered 19/11, 2009 at 5:15 Comment(0)
E
1

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

Etty answered 19/11, 2009 at 5:12 Comment(1)
I ran the example from the blog Remus posted, "select 'Will not divide by zero!' where (@id is NULL or 1/0=0)" did not cause an error when @id is NULLEastbound

© 2022 - 2024 — McMap. All rights reserved.