
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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)
Advertisements