I am trying to optimize a query that does something like this:
SELECT
...
CASE WHEN (condition) THEN (expensive function call #1)
ELSE (expensive fu
SQL is a declarative language. You express in a query the desired result and the server is free to choose whatever means to deliver those results. As such the order of evaluation of SQL epxressions is not determined and OR and AND evaluation short circuit does not occur.
However for CASE the documentation actually states that the order of evaluation occurs in the order of declaration and the evaluation stops after the first condition is met:
Evaluates
input_expression, and then in the order specified, evaluatesinput_expression=when_expressionfor eachWHENclause.Returns the
result_expressionof the firstinput_expression = when_expressionthat evaluates toTRUE.
That means that if you see the expression in the FALSE branch evaluated, your CASE condition is incorrect and sometimes evaluates to FALSE or UNKNOWN. Make sure that tri-values logic of SQL is taken into account (ie. you account for NULLs). Also make sure the data in the tables is the one you expect (ie. the condition really evaluates to FALSE 100% of the cases).
Is that an actual or estimated plan? Sql Server builds plans based on what it expects to do based on collected statistics, and that doesn't always jibe with what specific conditions you send it for one instance of a query run.