Thursday, November 4, 2010

MySQL - COALESCE on an empty string

COALESCE works only on NULLs.  If you have an empty string, COALESCE will return the empty string instead of the second value because the first value is not NULL.

How to return second value or column if first one is NULL or is blank:
SELECT IFNULL(NULLIF(col1,''),col2)
The inner NULLIF returns a NULL if col1 is blank.  The outer IFNULL returns col1 if it's not blank or NULL and col2 otherwise.

No comments:

Post a Comment