Tuesday, October 26, 2010

Exact use of COALESCE() function in sql server

COALESCE(arg1,arg2,...) is a pretty useful function in SQL. Suppose we have a table A having 3 columns FullName, CompleteName and DisplayName. Any of these columns can contain null values. Now we want to select the DisplayName from this table, but if it is null, then return FullName, if that is also null then return CompleteName. We can easily perform the same in one select statement as:

SELECT COALESCE(DisplayName, FullName, CompleteName) From A

This will return the first non-null value. And best thing is that COALESCE is an ANSI standard.

No comments:

Post a Comment