Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Coalesce with empty string

Tags:

sql

sql-server

I have the following:

Select Coalesce(Other,Industry) Ind from registration 

The thing is that Other can be an empty string or NULL. How do I get coalesce to work such that if Other is an empty string, Coalesce still returns Industry?

like image 361
Nate Pet Avatar asked Jun 24 '13 19:06

Nate Pet


People also ask

Does coalesce work with empty strings?

The Coalesce function evaluates its arguments in order and returns the first value that isn't blank or an empty string. Use this function to replace a blank value or empty string with a different value but leave non-blank and non-empty string values unchanged.

How do you use coalesce for NULL values in SQL?

The SQL Coalesce and IsNull functions are used to handle NULL values. During the expression evaluation process the NULL values are replaced with the user-defined value. The SQL Coalesce function evaluates the arguments in order and always returns first non-null value from the defined argument list.

Can coalesce return NULL?

If all the values in MySQL COALESCE() function are NULL then it returns NULL as the output. It means that this function does not find any non-NULL value in the list.

How do you pass an empty value in SQL?

There are two ways to replace NULL with blank values in SQL Server, function ISNULL(), and COALESCE(). Both functions replace the value you provide when the argument is NULL like ISNULL(column, '') will return empty String if the column value is NULL.


2 Answers

Use a CASE expression or NULLIF:

SELECT COALESCE(NULLIF(Other,''),Industry) Ind FROM registration 
like image 172
Lamak Avatar answered Oct 13 '22 15:10

Lamak


try this

Select Coalesce(nullif(Other,''),Industry) Ind from registration 
like image 35
rs. Avatar answered Oct 13 '22 16:10

rs.