Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is order of operational precedence in SQL Case statement?

Tags:

sql

sql-server

I am having a time discovering how to best write the following:

SET @SAMPLE = (SELECT CASE
WHEN @A < 0.01 AND @B < 0.01 THEN -1
WHEN @A < 0.01 THEN @B
ELSE @C
END )

I do not get what I expect here. I am finding that @SAMPLE contains 0.00 after running this. Thanks for any guidance.

like image 903
Taersious Avatar asked Mar 22 '23 04:03

Taersious


2 Answers

The CASE statement evaluates its conditions sequentially and stops with the first condition whose condition is satisfied

From your example, all one can deduct is that @B or @c is zero.

Operational precedence usually refers to which operator is first evaluated ("*" or "-", for example). Your question should probably be titled "Case evaluation order".

http://technet.microsoft.com/en-us/library/ms181765.aspx

like image 149
Rajesh Chamarthi Avatar answered Apr 27 '23 06:04

Rajesh Chamarthi


Without values I cannot be sure that this is what you mean but it seems that you are asking in what order does a case statement evaluate its WHEN clauses. If that indeed is the question then the answer is fairly simple. A CASE WHEN will return the value of the THEN statement for the first WHEN that is true and will stop evaluating immediately once it returns. This means that in your example @Sample will evaluate first WHEN to last WHEN (and within the WHEN it evaluates left to right) such that your logical checks are:

  1. Is @A < 0.01, TRUE continues on this same line while FALSE goes to the next line.
  2. If 1 was TRUE then @B < 0.01 is evaluated, TRUE returns -1 and the case statement ends while FALSE goes to the next line.
  3. If you are here either 1 or 2 is FALSE, either way @A < 0.01 is still evaluated again, if TRUE returns @B and the case statement ends while FALSE returns @C because all WHEN statements were FALSE.

Hope this helps.

like image 38
Daniel King Avatar answered Apr 27 '23 04:04

Daniel King