Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CONCAT'ing NULL fields

I have a table with three fields, FirstName, LastName and Email.

Here's some dummy data:

FirstName | LastName | Email Adam        West       [email protected] Joe         Schmoe     NULL 

Now, if I do:

SELECT CONCAT(FirstName, LastName, Email) as Vitals FROM MEMBERS 

Vitals for Joe is null, as there is a single null field. How do you overcome this behaviour? Also, is this the default behaviour in MS SQL Server?

like image 733
Thomas R Avatar asked Jun 23 '09 23:06

Thomas R


People also ask

How do you concatenate NULL values?

One way to concatenate multiple strings or columns is to use the "+" operator. For the rows where MiddleName is NULL, the concatenation result will be NULL.

Can we concatenate NULL values?

Concatenating Data When There Are NULL ValuesTo resolve the NULL values in string concatenation, we can use the ISNULL() function. In the below query, the ISNULL() function checks an individual column and if it is NULL, it replaces it with a space.

Can we concat string with NULL?

We cannot avoid null elements from being concatenated while using the String. join() method either. Let's see some approaches to avoid those null elements from being concatenated and get the result we would expect: “Java is great!”.


2 Answers

Try

ISNULL(FirstName, '<BlankValue>') -- In SQL Server IFNULL(Firstname, '<BlankValue>') -- In MySQL 

So,

CONCAT(ISNULL(FirstName,''),ISNULL(LastName,''),ISNULL(Email,'')) -- In SQL Server CONCAT(IFNULL(FirstName,''),IFNULL(LastName,''),IFNULL(Email,'')) -- In MySQL 

would return the same thing without the null issue (and a blank string where nulls should be).

like image 105
Stefan Mai Avatar answered Sep 21 '22 20:09

Stefan Mai


Look at CONCAT_WS

For example:

CONCAT_WS('',NULL,"TEST STRING","TEST STRING 2") 

Yields

TEST STRINGTEST STRING 2

This is easier than constructing IFNULL around everything. You can use an empty string as the separator.

like image 42
BILBO Avatar answered Sep 20 '22 20:09

BILBO