Tuesday, 28 May 2013

COALESCE() vs. ISNULL()

Having been reading the differences between COALESCE() and ISNULL() functions in T-SQL. I have found many other posts talking about this in details and thought put a summary table here for quick reference check.


COALESCE()
ISNULL()
Parameters (Syntax)
Accept multiple parameters
COALESCE ( expression [ ,...n ] )

Example:
SELECT COALESCE(NULL, NULL, 'foo')
Accept only two parameters
ISNULL( check_expression , replacement_value )

Example:
SELECT ISNULL(NULL, ISNULL(NULL, 'foo'))
Data Type Returned
Returns the data type of expression with the highest data type precedence. If all expressions are nonnullable, the result is typed as nonnullable.
Returns the same type as check_expression. If a literal NULL is provided as check_expression, returns the datatype of the replacement_value. If a literal NULL is provided as check_expression and no replacement_value is provided, returns an int.
Column Selected Into
Nullable column returned
Non-nullable column returned
SQL Function Type
Standard function (recommended to use)
Non-standard function
Performance Impact
Not recommended to use in the conditions of joins
In some cases where subquery is used in the expression can generate less efficient plan. E.g.,

SELECT COALESCE
(
    (SELECT a2.au_id
        FROM pubs..authors a2
        WHERE a2.au_id = a1.au_id),
    ''
)
FROM authors a1

Not recommended to use in the conditions of joins

References

COALESCE()
http://msdn.microsoft.com/en-us/library/ms190349.aspx

ISNULL()
http://msdn.microsoft.com/en-us/library/ms184325.aspx

Should I use COALESCE() or ISNULL()?
http://databases.aspfaq.com/database/coalesce-vs-isnull-sql.html

Can I have optional parameters to my stored procedures?
http://sqlserver2000.databases.aspfaq.com/can-i-have-optional-parameters-to-my-stored-procedures.html

No comments: