Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
442 views
in Technique[技术] by (71.8m points)

sql - SQLServer CASE expressions - short circuit evaluation?

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

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

The query plan shows that for even in cases where 100% of rows satisfy the WHEN clause, a substantial portion of the time is spent in calls to the result in the ELSE branch.

The only way I can make sense of this is to presume that SQLServer is evaluating both results, then only selecting one based on evaluation of the WHEN condition, but I can't find any definitive reference as to whether or not the results of a CASE statement are evaluated before the conditionals. Can anyone please clarify or point me to a reference?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...