I have searched unsuccessfully for a satisfactory explanation on the difference between GROUP_CONCAT()
and CONCAT_WS()
.
Are they as closely related as I think they are?
What are the differences in usage, speed, etc. between these two functions?
Both CONCAT() and CONCAT_WS() functions are used to concatenate two or more strings but the basic difference between them is that CONCAT_WS() function can do the concatenation along with a separator between strings, whereas in CONCAT() function there is no concept of the separator.
GROUP_CONCAT is a function which concatenates/merges the data from multiple rows into one field. It is a GROUP BY function which returns a string if the group contains at least 1 non-null value, if it does not, it returns a Null value.
The CONCAT_WS() function adds two or more strings together with a separator.
GROUP_CONCAT
is used when you want to have non-NULL values from different column rows in a single row. For this you need to have GROUP BY to work.
CONCAT_WS
is to join two or more strings.
Example,
GROUP_CONCAT(CONCAT_WS(' ', firstname, lastname) ORDER BY id ASC SEPARATOR ',');
Outputs something like,
John Doe,Blah Blah,Tom Cruise,Lorem Ipsum
here space between the name is because of CONCAT_WS
, while whole result in one row is because of GROUP_CONCAT
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