From this question, a neat answer about using COALESCE to simplify complex logic trees. I considered the problem of short circuiting.
For instance, in functions in most languages, arguments are fully evaluated and are then passed into the function. In C:
int f(float x, float y) {
return x;
}
f(a, a / b) ; // This will result in an error if b == 0
That does not appear to be a limitation of the COALESCE
"function" in SQL Server:
CREATE TABLE Fractions (
Numerator float
,Denominator float
)
INSERT INTO Fractions VALUES (1, 1)
INSERT INTO Fractions VALUES (1, 2)
INSERT INTO Fractions VALUES (1, 3)
INSERT INTO Fractions VALUES (1, 0)
INSERT INTO Fractions VALUES (2, 0)
INSERT INTO Fractions VALUES (3, 0)
SELECT Numerator
,Denominator
,COALESCE(
CASE WHEN Denominator = 0 THEN 0 ELSE NULL END,
CASE WHEN Numerator <> 0 THEN Numerator / Denominator ELSE NULL END,
0
) AS TestCalc
FROM Fractions
DROP TABLE Fractions
If it were evaluating the second case when Denominator = 0, I would expect to see an error like:
Msg 8134, Level 16, State 1, Line 1
Divide by zero error encountered.
I found some mentions related to Oracle. And some tests with SQL Server. Looks like the short-circuiting might break down when you include user-defined functions.
So, is this behavior supposed to be guaranteed by the ANSI standard?
SELECT COALESCE(1, (SELECT 1/0))
runs without error and shows that it short-circuits. The interpreter sees it as a shortenedCASE
statement. – Whitacre