-
Couldn't load subscription status.
- Fork 3.3k
Description
It seems that COALESCE may be expanded to a CASE/WHEN, which causes the expression to get evaluated twice (link); ISNULL apparently doesn't have this behavior. This has a performance impact (i.e. when the expression is a heavy subquery), but can also lead to incorrect results when the expression is non-deterministic and can return different results each time it's evaluated:
CREATE TABLE Foo (A int, B int);
INSERT INTO Foo (A, B) VALUES (1, NULL), (2, 2), (3, NULL);
SELECT COALESCE((SELECT TOP 1 B FROM Foo ORDER BY NEWID() ASC), 0); -- sometimes returns NULL!Also, check if the same thing happens on other databases, i.e. whether this should be a SQL Server-only change or something with a wider scope.
SQL Server documentation detailing all the above, plus the differences between COALESCE and ISNULL. See also (this post) on that.
Thanks for @John0King for reporting this (see #22243 (comment)).