Pages

Monday, June 30, 2014

Difference Between COALESCE and ISNULL

ISNULL is a T-SQL function to replace NULL values as COALESCE does. At some cases these two functions get the same results but there are some differences. Below is a summary of their differences and I hope that it will help you decide which function to use when you need to determine the one with better performance or better concurrency control.


COALESCE ISNULL
Standard ANSI SQL? Yes No (Only for T-SQL)
Numbers of Parameters Two or more parameters. Two parameters only.
Data type determination of the resulting expression Determined by the data type of parameters with the highest precedence Determined by data type of the first parameter
Allow both inputs to be untyped NULLs?
No. For SELECT COALESCE(NULL, NULL); , it will return an error. You need to have at least one of the null values be a typed NULL. 

SELECT COALESCE(CAST(NULL AS INT), NULL);

Yes. For SELECT ISNULL(NULL, NULL); it will return a NULL typed as an integer.
NULLability of the resulting expression Considered to be NULL with non-null parameters. Always considered NOT NULLable
Working with subquery as input parameters When executing COALESCE((subquery), 1), the subquery is evaluated twice.  you can get different results depending on the isolation level of the query. Evaluated only once.

No comments:

Post a Comment