65.9K
CodeProject is changing. Read more.
Home

Find First Not Null Value From Different Columns: TIP# 47

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Sep 14, 2014

CPOL

1 min read

viewsIcon

5044

Find first not null value from different columns

Problem

Sometimes, it might be possible that we need not null value only from particular columns and if all columns have null value, then we provide a default value.

Let's understand this by a general and very interesting example.

Suppose a friend comes to your house and you want to give him a treat, then you check your first column or we can say first option “Is there anything to eat?” if that value is null then you go for second column or we can say second option “Is there anything to drink?”

If that value is also null, then you will choose 3rd or default option and ask friend to give you treat.

Isn’t it simple Smile? Just kidding Open-mouthed smile.

Let’s understand now with adventurework’s product table.

Suppose we want to fetch productId, productname, productnumber, and any property (either color, class) and if both the columns (color, class) are null, then we need to display “No Property found” in the column value.

So, I wrote the following query to achieve this:

SELECT PRODUCTID ,
      Name,
     ProductNumber,
COALESCE(Color,class,’No Property found’) As productProperty
FROM [Production].[Product]

COALESCE

So if you observe the above figure, you will find in the records where color found color value appear and if color value is null and class value found, the class value appears and if both color and class value are null, then we provide simple value which is “No Property found”.

I hope this may help you.

Thanks & enjoy!

Filed under: CodeProject, DENALI, Sql server, SQL SERVER 2008 - R2, SQL SERVER 2014, TIPS
Tagged: COLEASCE, ISNULL, NULL