Concatenate data from multiple rows using GROUP_CONCAT() in MySQL?


Let us first create a table −

mysql> create table DemoTable (CountryName varchar(100));
Query OK, 0 rows affected (1.01 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('US');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values('AUS');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('UK');
Query OK, 1 row affected (0.19 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-------------+
| CountryName |
+-------------+
| US          |
| AUS         |
| UK          |
+-------------+
3 rows in set (0.00 sec)

Here is the query to concat multiple rows. We are creating a procedure −

mysql> DELIMITER //
mysql> CREATE PROCEDURE searchDemo(in stringValue varchar(255), out output text)
   BEGIN
      select group_concat(distinct CountryName order by CountryName) into output from DemoTable where
      CountryName like stringValue;
   END
   //
Query OK, 0 rows affected (0.18 sec)
mysql> DELIMITER ;

Call the stored procedure with the help of call command −

mysql> call searchDemo('U%',@output);
Query OK, 1 row affected, 2 warnings (0.04 sec)

Let us check the value of variable @output −

mysql> select @output;

This will produce the following output −

+---------+
| @output |
+---------+
| UK,US   |
+---------+
1 row in set (0.00 sec)

Updated on: 22-Aug-2019

186 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements