Thursday, September 26, 2019

MySQL: GROUP_CONCAT


By  | August 24, 2014
MySQL GROUP_CONCAT Function
In this tutorial, we will learn how to use the MySQL GROUP_CONCAT function to concatenate strings from a group of values with various options.
The following illustrates the GROUP_CONCAT function:


The maximum length of the return string is 1024 by default.
You can extend the returned value’s length by setting the group_concat_max_len system variable at SESSION or GLOBAL level.
MySQL GROUP_CONCAT Examples
Let’s take a look at the countries table in the sample database.

To get all countries as a (,) string, you use the GROUP_CONCAT function as follows:


To remove the duplicate country names, you have to add the DISTINCT clause as the following query:


To sort the country names before concatenating other than ASC, you have to use the ORDER BY clause as follows:


To change the default separator of the returned string from a comma (,) to a any other, you have to use the SEPARATOR clause as the following query:


Let’s take a look at the states table associated with countries table:


To get country name and all associated state names as concatenated string using the following query:


To get country name and all associated state names with their status(By using CONCAT function) as concatenated string using the following query:


To get country name and all associated state names with their status(By using CONCAT_WS function) as concatenated string using the following query:


No comments:

Post a Comment