简体   繁体   中英

SQL case-when-else statement efficiency

When I use this statement;

UPDATE TABLE
   SET FIELD = CASE
               WHEN NAME = 'a' THEN (SELECT NO FROM TABLE_TWO WHERE NAME = 'a')
               ELSE 'x' END
 WHERE FIELD_TWO = 1

if TABLE.NAME != 'a' will the select SQL executed nevertheless? Moreover, a little extra question, do you think it is proper to have such logic in SQL code for any given product? I think having any logic in SQL makes its coverage very difficult, and hard to maintain, what do you think?

edit: select statement only returns a single value, ignore the case where it can return multiple values, that case is not in the scope of this question.

I think it would be easier to read and maintain, when you split it into two UPDATE-statements like this:

UPDATE TABLE SET FIELD = (SELECT TOP 1 NO FROM TABLE_TWO WHERE NAME = 'a')
            WHERE FIELD_TWO = 1
              AND NAME='a'
UPDATE TABLE SET FIELD = 'x' 
            WHERE FIELD_TWO = 1
            AND NAME != 'a'

It lets you add more cases easily and you can generalize the cases if there are more of them, like:

UPDATE TABLE SET FIELD = (SELECT TOP 1 NO FROM TABLE_TWO WHERE NAME = TABLE.FIELD)
            WHERE FIELD_TWO = 1
              AND NAME IN ('a','b','c')

If I were you, I would use a variable so that case doesn't compute a scalar value everytime. Something like following:

DECLARE @myVar VARCHAR(10);

SELECT TOP 1 @myVar = NO FROM TABLE_TWO WHERE NAME = 'a';

UPDATE TABLE
   SET FIELD = CASE
               WHEN NAME = 'a' THEN @myVar
               ELSE 'x' END
 WHERE FIELD_TWO = 1

The Oracle manual claims that it does short-circuit evaluation:

Oracle Database uses short-circuit evaluation . For a simple CASE expression, the database evaluates each comparison_expr value only before comparing it to expr , rather than evaluating all comparison_expr values before comparing any of them with expr

In your case comparison_expr is the WHEN NAME = 'a' part and if the manual is right, the database will not run the select if name has a different value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM