How to use GROUP BY to concatenate strings in MySQL and how to set a separator for the concatenation?

MySQLMySQLi Database

To concatenate strings in MySQL with GROUP BY, you need to use GROUP_CONCAT() with a SEPARATOR parameter which may be comma(‘) or space (‘ ‘) etc.

The syntax is as follows:

SELECT yourColumnName1,GROUP_CONCAT(yourColumnName2 SEPARATOR ‘yourValue’) as anyVariableName FROM yourTableName GROUP BY yourColumnName1;

To understand the above syntax, let us create a table. The query to create a table is as follows:

mysql> create table GroupConcatenateDemo
   -> (
   -> Id int,
   -> Name varchar(20)
   -> );
Query OK, 0 rows affected (0.99 sec)

Insert some records in the table using insert command. The query to insert record is as follows:

mysql> insert into GroupConcatenateDemo values(10,'Larry');
Query OK, 1 row affected (0.41 sec)
mysql> insert into GroupConcatenateDemo values(11,'Mike');
Query OK, 1 row affected (0.18 sec)
mysql> insert into GroupConcatenateDemo values(12,'John');
Query OK, 1 row affected (0.14 sec)
mysql> insert into GroupConcatenateDemo values(10,'Elon');
Query OK, 1 row affected (0.63 sec)
mysql> insert into GroupConcatenateDemo values(10,'Bob');
Query OK, 1 row affected (0.12 sec)
mysql> insert into GroupConcatenateDemo values(11,'Sam');
Query OK, 1 row affected (0.14 sec)

Display all records from the table using select statement. The query is as follows:

mysql> select *from GroupConcatenateDemo;

The following is the output:

+------+-------+
| Id   | Name  |
+------+-------+
|   10 | Larry |
|   11 | Mike  |
|   12 | John  |
|   10 | Elon  |
|   10 | Bob   |
|   11 | Sam   |
+------+-------+
6 rows in set (0.00 sec)

Here is the query that use GROUP BY to concatenate the strings in MySQL. Perform GROUP BY on the basis of Id and concatenate the strings using GROUP_CONCAT() function in MySQL.

The query is as follows:

mysql> select Id,group_concat(Name SEPARATOR ',') as GroupConcatDemo from GroupConcatenateDemo
   -> group by Id;

The following is the output:

+------+-----------------+
| Id   | GroupConcatDemo |
+------+-----------------+
|   10 | Larry,Elon,Bob  |
|   11 | Mike,Sam        |
|   12 | John            |
+------+-----------------+
3 rows in set (0.00 sec)
raja
Published on 26-Feb-2019 12:22:11
Advertisements