How to concatenate all values of a single column in MySQL?


You can use group_concat() along with concat() to concatenate all values of a single column. Let us first create a table −

mysql> create table DemoTable
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, FirstName varchar(20)
   );
Query OK, 0 rows affected (0.73 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(FirstName) values('John');
Query OK, 1 row affected (0.15 sec)

mysql> insert into DemoTable(FirstName) values('Larry');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable(FirstName) values('Chris');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable(FirstName) values('Robert');
Query OK, 1 row affected (0.13 sec)

mysql> insert into DemoTable(FirstName) values('David');
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+-----------+
| Id | FirstName |
+----+-----------+
|  1 | John      |
|  2 | Larry     |
|  3 | Chris     |
|  4 | Robert    |
|  5 | David     |
+----+-----------+
5 rows in set (0.00 sec)

Following is the query to concatenate all values of a single column in MySQL.

mysql> select group_concat(concat('"', FirstName, '"')) AS FirstName from DemoTable;

This will produce the following output −

+-----------------------------------------+
| FirstName                               |
+-----------------------------------------+
| "John","Larry","Chris","Robert","David" |
+-----------------------------------------+
1 row in set (0.05 sec)

Updated on: 30-Jul-2019

783 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements