As we already know, MySQL has two functions to concatenate strings: CONCAT
and CONCAT_WS
.
Answering a question, I saw that CONCAT
it does not return the expected results when at least one of the values is equal to NULL
.
When is it then recommended to use CONCAT
and when to use CONCAT_WS
?
I. What the documentation says
Let's first see what the documentation explains about both functions:
CONCAT()
In other words, any value
NULL
that goes into aCONCAT
nullifies all other values.CONCAT_WS()
II. Determining which one to use in a real scenario
Suppose a table layout like this:
(a) The problem of
CONCAT
with valuesNULL
The table layout shown above is a common layout, in fact any table could have columns like
apellido_paterno
, that is, columns that take valuesNULL
. And not only that, in any insert that does not assign values to those columns, its default value will beNULL
.That means, if we do an insert like this:
the column
apellido_paterno
will receive by default the valueNULL
.If we use
CONCAT
in our tablepersona
:The result, in the case of
Pedro Pérez
will be:In other words, neither Pedro, nor Pérez, nor anything... just
NULL
. Truly terrible right?Note that
NULL
and an empty string are not the same thing. Let's try anotherINSERT
:Since you are observant, you have seen that the column
apellido_paterno
is receiving an empty string''
.And we'll see that he
CONCAT()
's a friend of empty strings... It's just that heCONCAT()
has his preferences... it's not fair, no! :)The result of the
SELECT
above forJuan Arias
will be:The problem is that when no value is given explicitly, the column gets a value
NULL
and that's terrible if we useCONCAT
.(b) The behavior of
CONCAT_WS()
Let's see how he behaves
CONCAT_WS()
with our friendPedro Pérez
:It would result in:
And with
Juan Arias
?:This
CONCAT_WS
then is almost a wonder!According to its syntax, we have to put the separator at the beginning only, and then the list of columns or values that we want to concatenate. If the spacer is the same that's great, but what if I need different spacers? .
We can do it! , putting an empty string as a separator and concatenating the columns and values as we do with
CONCAT()
, that is, handmade :The result would be:
Good, but... there is a blank space when some data is missing! That has a solution, it's up to you to find it.
III. conclusion
Since
CONCAT()
:NULL
And seen that
CONCAT_WS()
:NULL
CONCAT()
in cases where the separator changesWe can conclude that it can be used
CONCAT_WS()
in all cases and if we want to use itCONCAT()
we must be totally sure that all the values involved are noneNULL
.A full demo of the code used in the answer can be found here .