Pages

Friday, June 10, 2011

ISNULL VS COALESCE

For example Production.Product table records
ClassColorProductNumber
cl1NullNull
cl2NullNull
Nullco3Null
Nullco4Null
NullNullpn5
cl6co6Null
cl7co7pn7



ISNULL - if the first value is null, it will pick second value, if not first value will be return. Only 2 arguments can pass. Replaces NULL with the specified replacement value.

ISNULL ( check_expression , replacement_value )

SELECT  ISNULL(Class, Color) AS FirstNotNull FROM Production.Product
cl1
cl2
co3
co4
null
cl6
pn7

Coalesce returns the first non-null column from more than one columns
COALESCE ( expression [ ,...n ] )

SELECT  COALESCE(Class, Color, ProductNumber) AS FirstNotNull FROM Production.Product
cl1
cl2
co3
co4
pn5
cl6
pn7

No comments:

Post a Comment