TIs ISNULL() a lazy function?
That is, if i code something like the following:
SELECT ISNULL(MYFIELD, getMyFunction()) FROM MYTABLE
will it always evaluate getMyFunction() or will it only evaluate it in the case where MYFIELD is actually null?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It’s whichever it thinks will work best.
Now it’s functionally lazy, which is the important thing. E.g. if
col1is avarcharwhich will always contain a number whencol2is null, thenWill work.
However, it’s not specified whether it will try the cast before or simultaneously with the null-check and eat the error if
col2isn’t null, or if it will only try the cast at all ifcol2is null.At the very least, we would expect it to obtain
col1in any case because a single scan of a table obtaining 2 values is going to be faster than two scans obtaining one each.The same SQL commands can be executed in very different ways, because the instructions we give are turned into lower-level operations based on knowledge of the indices and statistics about the tables.
For that reason, in terms of performance, the answer is “when it seems like it would be a good idea it is, otherwise it isn’t”.
In terms of observed behaviour, it is lazy.
Edit: Mikael Eriksson’s answer shows that there are cases that may indeed error due to not being lazy. I’ll stick by my answer here in terms of the performance impact, but his is vital in terms of correctness impact across at least some cases.