MySQL CONCAT() Returning NULL Even Though Values Exist

January 24th, 2014 - Posted by Steve Marks to MySQL, Web Development.

The MySQL CONCAT() function is used to concatenate two or more columns or strings together.

I had a scenario earlier today where, when concatenating a few columns together the outcome would always be NULL. An example of this query was as follows where I was concatenating a series of address fields into a single value:

    CONCAT(address_1, ' ', address_2, ' ', address_3, ' ', postcode) AS address

Even though I knew at least one of the address fields contained a valid value, the result would always be NULL. After not being able to find an obvious solution for myself I turned to the documentation where I would eventually obtain the reason.

The Cause

In the MySQL documentation it states:

CONCAT() returns NULL if any argument is NULL.

My address fields could, and did, contain NULL values so this would seem to explain the issue I was experiencing.

The Solution

My initial thought when coming to solve the issue was to try and do some crazy IF on each field like so:

        IF (ISNULL(address_1), '', address_1), ' ', 
        IF (ISNULL(address_2), '', address_2), ' ', 
        IF (ISNULL(address_3), '', address_3), ' ', 
        IF (ISNULL(postcode), '', postcode)
    ) AS address

To be honest, I’m not sure if this would even work as fortunately I found a simpler solution short after. The solution that worked for me came in the form of a similar MySQL function called CONCAT_WS():

    CONCAT_WS(' ', address_1, address_2, address_3, postcode) AS address

As you can see, this is a much cleaner approach to the one I originally had planned and, unlike CONCAT(), CONCAT_WS() doesn’t return NULL if just one of the fields is NULL. The only difference between the final solution and the original query is the order of the parameters. Note how CONCAT_WS() expects the first parameter to be the separator?

Note: The final solution only works if the separator between each field will the same. If you plan on having different separators then the more advanced option proposed first might be the best option.

This entry was posted on Friday, January 24th, 2014 at 2:07 pm by +Steve Marks and is filed under MySQL, Web Development. You can follow any responses to this entry through the RSS 2.0 feed.

Fear not, we won't publish this

Comments (0)

No comments have been left yet. Be the first