How to Handle MySQL CONCAT Function Returning NULL for Any Field Containing NULL?

I’m using the CONCAT function in MySQL to combine the user’s first name, last name, and username fields into one string. However, if any of the fields contain NULL, the CONCAT function returns NULL for the entire string. How can I solve this issue and get the CONCAT function to ignore NULL values?

CONCAT( first_name, " ", last_name, " (", username, ")" )

You can try to convert the NULL values with empty string using COALESCE or use CONCAT_WS which ignore null values.

CONCAT( COALESCE(first_name,''), ' ', COALESCE(last_name,''), ' (', username, ')' )

OR

CONCAT_WS( '', first_name, ' ', last_name, ' (', username, ')' )

CONCAT_WS concatenates with separator, allows you to specify a separator between the fields you want to concatenate. The first param is empty separator. You can use it for SPACE or other separator. If any field contains NULL, CONCAT_WS ignores it and continues with the concatenation.