SQLServer CASE expressions - short circuit evaluation?

前端 未结 2 1178
眼角桃花
眼角桃花 2020-12-11 05:32

I am trying to optimize a query that does something like this:

SELECT
   ...
   CASE WHEN (condition) THEN (expensive function call #1)
   ELSE (expensive fu         


        
相关标签:
2条回答
  • 2020-12-11 05:52

    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, evaluates input_expression = when_expression for each WHEN clause.

    • Returns the result_expression of the first input_expression = when_expression that evaluates to TRUE.

    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).

    0 讨论(0)
  • 2020-12-11 06:02

    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.

    0 讨论(0)
提交回复
热议问题