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?
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.
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.
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!”.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With