Profile

Monday 25 July 2011

SQL COALESCE: Whichever not null.

Sometimes we need to retrieve information from multiple columns from a table whichever is not null. In such situation COALESCE can be used in SQL query

I picked a sample table ProductListPriceHistory. It shows each product's ID and its list price. Some of them have both StartDate and EndDate. Some of them have either one only.  


Assume those date indicated as the availability of each product, I want to retrieve the information based on the following conditions:
1.) if both StartDate and EndDate are not NULL, retrieve the first column (StartDate)
2.) if either StartDate or EndDate is NULL, retrieve whichever column is NOT NULL

Therefor I wrote a query like this:

     USE AdventureWorks2008
     GO

     SELECT ProductID,COALESCE(StartDate,EndDate)TodayPrice, ListPrice
     FROM
     Production.ProductListPriceHistory

After execute the query, it retrieve the value from StartDate and EndDate whichever is not null and input it into TodayPrice column.

No comments: