How to quote values of single column using GROUP_CONCAT and CONCAT with DISTINCT in MySQL?


For this, you can use group_concat() along with replace(). Let us first create a table −

mysql> create table DemoTable1799
     (
     EmployeeId varchar(20)
     );
Query OK, 0 rows affected (0.00 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1799 values('101,102,103,104');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1799 values('106,109');
Query OK, 1 row affected (0.00 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1799;

This will produce the following output:

+-----------------+
| EmployeeId      |
+-----------------+
| 101,102,103,104 |
| 106,109         |
+-----------------+
2 rows in set (0.00 sec)

Here is the query to quote values of single column using group_concat and concat with distinct −

mysql> select group_concat(distinct concat("'", replace(EmployeeId, "," , "','") , "'")) as Output from DemoTable1799;

This will produce the following output −

+-------------------------------------+
| Output                              |
+-------------------------------------+
| '101','102','103','104','106','109' |
+-------------------------------------+
1 row in set (0.00 sec)

Updated on: 23-Dec-2019

293 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements